paramiko的简单使用
1.封装
近期工作中需要从一个服务器上执行某些脚本,所以需要ssh到该服务器执行命令,paramiko就是一个很不错的选择
为了方便使用,以下是简单的封装
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 | 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命令让它后台执行
例如
1 2 3 | 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) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
2022-04-09 Windows10下安装MySQL8.0
2022-04-09 MySQL允许远程登录的授权方法