Download pipeline/ssh_handler.py from ddochi132/GS_APP: direct link, hf CLI and curl.
- Browser
- Download file 7.22 kB
-
https://huggingface.co/spaces/ddochi132/GS_APP/resolve/main/pipeline/ssh_handler.py
- Command line
-
hf download hf://spaces/ddochi132/GS_APP/pipeline/ssh_handler.py
-
curl -L -o ssh_handler.py https://huggingface.co/spaces/ddochi132/GS_APP/resolve/main/pipeline/ssh_handler.py
7.22 kB
| 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) | |