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)

  

posted on   帅胡  阅读(287)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
历史上的今天:
2022-04-09 Windows10下安装MySQL8.0
2022-04-09 MySQL允许远程登录的授权方法

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示