paramiko的简单使用
1.封装
近期工作中需要从一个服务器上执行某些脚本,所以需要ssh到该服务器执行命令,paramiko就是一个很不错的选择
为了方便使用,以下是简单的封装
import paramiko class ParamikoSftp: def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = super(ParamikoSftp, cls).__new__(cls) return cls._instance def __init__(self, ip, port, username, password): self.transport = paramiko.Transport((ip, port)) self.transport.connect(username=username, password=password) self.sftp = paramiko.SFTPClient.from_transport(self.transport) self.client = paramiko.SSHClient() self.client._transport = self.transport def put(self, local_file, remote_path): try: self.sftp.put(local_file, remote_path) return True, None except Exception as e: return False, repr(e) def get(self, remote_path, local_path): try: self.sftp.get(remote_path, local_path) return True, None except Exception as e: return False, repr(e) def exec_command(self, cmd): try: _, stdout, stderr = self.client.exec_command(cmd) return stdout.read().decode('utf-8'), stderr.read().decode('utf-8') except Exception as e: print("error", e) return False, repr(e) def close(self): self.sftp.close() self.client.close() self.transport.close()
2.执行长时间任务
有些脚本是需要执行很长时间的,比如说几个小时那种,直接调用exec_command()的话它会等待脚本执行完的,所以我们需要使用nohup命令让它后台执行
例如
paramiko_sftp = ParamikoSftp(**finance_ssh_config) # 通过配置实例化对象 cmd_python = "nohup python /xxx/main.py > /xxx/nohup.out 2>&1 &" stdout, stderr = paramiko_sftp.exec_command(cmd_python)