# 文件路径: commonLib/remote/sftpClient.pyimport osimport paramikofrom loguru import loggerclass SftpClient:def __init__(self, host: str, port: int = 22, username: str = "", password: str = ""):self.host = hostself.port = portself.username = usernameself.password = passwordself.ssh = Noneself.sftp = Nonedef connect(self) -> bool:try:self.ssh = paramiko.SSHClient()self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())self.ssh.connect(hostname=self.host, port=self.port, username=self.username, password=self.password, timeout=3)self.sftp = self.ssh.open_sftp()return Trueexcept Exception as e:logger.info(f"[SFTP] 连接失败: {e}")return Falsedef exec_remote_command(self, command: str, get_output: bool = True) -> tuple[bool, str]:"""在远程主机上通过 SSH 执行 shell 命令。参数:command: 要执行的命令字符串,例如 "mkdir -p /home/user/logs"get_output: 是否获取命令输出(默认为 True)返回:(success: bool, output: str)"""if not self.ssh:return False, "SSH 未连接"try:stdin, stdout, stderr = self.ssh.exec_command(command)stdout.channel.recv_exit_status() # 等待命令完成if get_output:result = stdout.read().decode().strip()error = stderr.read().decode().strip()if error:return False, errorreturn True, resultreturn True, ""except Exception as e:return False, str(e)def _mkdir_p(self, remote_directory: str):"""通过 SSH 远程创建目录(类似 mkdir -p)"""success, result = self.exec_remote_command(f"mkdir -p '{remote_directory}'")if success:logger.info(f"[SFTP] 创建远程目录成功: {remote_directory}")else:logger.info(f"[SFTP] 创建远程目录失败: {remote_directory}, 原因: {result}")raise Exception(result)def upload_file(self, local_path: str, remote_path: str) -> bool:if not self.sftp:logger.info("[SFTP] 未连接,无法上传")return Falsetry:remote_dir = os.path.dirname(remote_path)self._mkdir_p(remote_dir) # 自动创建远程目录self.sftp.put(local_path, remote_path)logger.info(f"[SFTP] 上传成功: {local_path} → {remote_path}")return Trueexcept Exception as e:logger.info(f"[SFTP] 上传失败: {e}")return Falsedef download_file(self, remote_path: str, local_path: str) -> bool:if not self.sftp:logger.info("[SFTP] 未连接,无法下载")return Falsetry:os.makedirs(os.path.dirname(local_path), exist_ok=True)self.sftp.get(remote_path, local_path)logger.info(f"[SFTP] 下载成功: {remote_path} → {local_path}")return Trueexcept Exception as e:logger.info(f"[SFTP] 下载失败: {e}")return Falsedef close(self):if self.sftp:self.sftp.close()if self.ssh:self.ssh.close()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。