File size: 7,222 Bytes
02bca29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import os
import socket
import select
import threading
import paramiko
import stat
from pathlib import Path


class SSHTunnel:
    """SSH 로컬 포트 포워딩 터널 (localhost:local_port → remote:remote_port)."""

    def __init__(self, transport, local_port: int, remote_port: int):
        self.transport = transport
        self.local_port = local_port
        self.remote_port = remote_port
        self._server: socket.socket | None = None
        self._running = False

    def start(self):
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._server.bind(("127.0.0.1", self.local_port))
        self._server.listen(5)
        self._server.settimeout(1.0)
        self._running = True
        threading.Thread(target=self._accept_loop, daemon=True).start()

    def stop(self):
        self._running = False
        if self._server:
            self._server.close()

    def _accept_loop(self):
        while self._running:
            try:
                client, _ = self._server.accept()
                threading.Thread(
                    target=self._forward, args=(client,), daemon=True
                ).start()
            except socket.timeout:
                continue
            except OSError:
                break

    def _forward(self, client_sock: socket.socket):
        try:
            channel = self.transport.open_channel(
                "direct-tcpip",
                ("127.0.0.1", self.remote_port),
                client_sock.getpeername(),
            )
        except Exception:
            client_sock.close()
            return
        if channel is None:
            client_sock.close()
            return
        while True:
            r, _, _ = select.select([client_sock, channel], [], [], 5.0)
            if client_sock in r:
                data = client_sock.recv(8192)
                if not data:
                    break
                channel.sendall(data)
            if channel in r:
                data = channel.recv(8192)
                if not data:
                    break
                client_sock.sendall(data)
        channel.close()
        client_sock.close()


class SSHHandler:
    def __init__(self):
        self.client = None
        self.sftp   = None

    # ─── 연결 ────────────────────────────────────────────────────────────────
    def connect(self, host: str, port: int, username: str, password: str):
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(host, port=port, username=username, password=password, timeout=30)
        self.sftp = self.client.open_sftp()

    def close(self):
        if self.sftp:
            self.sftp.close()
        if self.client:
            self.client.close()

    # ─── 원격 디렉토리 생성 ──────────────────────────────────────────────────
    def mkdir_p(self, remote_path: str):
        parts = remote_path.replace("\\", "/").split("/")
        cur = ""
        for p in parts:
            if not p:
                cur = "/"
                continue
            cur = cur.rstrip("/") + "/" + p
            try:
                self.sftp.stat(cur)
            except FileNotFoundError:
                try:
                    self.sftp.mkdir(cur)
                except PermissionError:
                    raise PermissionError(
                        f"서버에서 디렉토리 생성 권한 없음: {cur}\n"
                        "원격 경로를 해당 계정이 쓸 수 있는 경로로 변경하세요.\n"
                        "예) /home/<username>/gs_workspace"
                    )

    # ─── 디렉토리 업로드 ─────────────────────────────────────────────────────
    def upload_directory(self, local_dir: str, remote_dir: str, log_callback=None):
        """로컬 디렉토리 전체를 원격으로 업로드."""
        self.mkdir_p(remote_dir)
        for root, dirs, files in os.walk(local_dir):
            rel_root  = os.path.relpath(root, local_dir)
            rem_root  = remote_dir + "/" + rel_root.replace("\\", "/")
            rem_root  = rem_root.replace("/./", "/")

            for d in dirs:
                self.mkdir_p(rem_root + "/" + d)

            for f in files:
                local_file  = os.path.join(root, f)
                remote_file = rem_root + "/" + f
                if log_callback:
                    log_callback(f"  업로드: {f}")
                self.sftp.put(local_file, remote_file)

    # ─── 파일 다운로드 ───────────────────────────────────────────────────────
    def download_file(self, remote_path: str, local_path: str, log_callback=None):
        os.makedirs(os.path.dirname(local_path), exist_ok=True)
        if log_callback:
            log_callback(f"다운로드 중: {remote_path}")
        self.sftp.get(remote_path, local_path)

    # ─── 원격 명령 실행 ──────────────────────────────────────────────────────
    def exec(self, command: str, timeout: int = None) -> tuple:
        """
        Returns: (stdout_str, stderr_str, exit_code)
        """
        _, stdout, stderr = self.client.exec_command(command, timeout=timeout)
        exit_code = stdout.channel.recv_exit_status()
        return stdout.read().decode(), stderr.read().decode(), exit_code

    def exec_background(self, command: str, log_file: str) -> None:
        """백그라운드로 실행하고 로그 파일에 출력 저장."""
        full_cmd = f"nohup {command} > {log_file} 2>&1 &"
        self.client.exec_command(full_cmd)

    def read_remote_tail(self, remote_path: str, lines: int = 30) -> str:
        """원격 로그 파일의 마지막 N줄 읽기."""
        try:
            stdout, _, _ = self.exec(f"tail -n {lines} {remote_path}")
            return stdout
        except Exception:
            return ""

    def file_exists(self, remote_path: str) -> bool:
        try:
            self.sftp.stat(remote_path)
            return True
        except FileNotFoundError:
            return False

    def find_file(self, remote_dir: str, filename: str) -> str:
        """원격 디렉토리에서 파일명으로 검색. 첫 번째 결과 반환."""
        stdout, _, _ = self.exec(f"find {remote_dir} -name '{filename}' 2>/dev/null | head -1")
        return stdout.strip()

    def write_remote_file(self, remote_path: str, content: str):
        """원격 파일에 텍스트 내용 작성 (SFTP)."""
        import io
        with self.sftp.open(remote_path, "w") as f:
            f.write(content)