python 通过paramiko自动上传到linux服务器并运行

python 通过paramiko自动上传到linux服务器并运行

import paramiko, time, sys, traceback, os


class SSHUtils:
    def __init__(self, ip, username, passwd, port=22):
        self.ip = ip
        self.port = port
        self.username = username
        self.passwd = passwd

    def upload(self, file_path, origin_file_path):
        trans = paramiko.Transport((self.ip, self.port))
        trans.connect(username=self.username, password=self.passwd)
        sftp = paramiko.SFTPClient.from_transport(trans)
        try:
            sftp.put(file_path, origin_file_path)
            trans.close()
            print('上传成功')
        except Exception as e:
            print(e)

    def exec_ssh_command(self, ssh_command):
        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            # 连接服务器
            ssh.connect(hostname=self.ip, port=self.port, username=self.username, password=self.passwd, timeout=10)
            client = ssh.invoke_shell()
            client.send(ssh_command + '\n')
            res = ''
            while not res.endswith('# '):
                time.sleep(1)
                res += client.recv(65535).decode('utf-8')

            ssh.close()
            return res
        except:
            type, value, tb = sys.exc_info()
            return traceback.format_exception(type, value, tb)

    def exec_command(self, ssh_command):
        # 创建一个ssh对象
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接服务器
        ssh.connect(hostname=self.ip, port=self.port, username=self.username, password=self.passwd, timeout=10)
        # 执行shell命令,返回的是一个元组
        stdin, stdout, stderr = ssh.exec_command(ssh_command)
        # 获取输出结果,decode('utf-8')解码是为了存在中文能够正常显示
        result = stdout.read().decode('utf-8')
        ssh.close()
        return result


if __name__ == '__main__':
    f_path = r"c:/xxxx/admin.jar"
    o_file_path = r"/opt/service/admin.jar"
    stop_cmd = "cd /opt/service/ && sh admin.sh stop && rm -rf admin.jar"
    start_cmd = "cd /opt/service/ && sh admin.sh start"
    ipaddr = "xxx.xx.xx.xxx"
    user_name = "xxx"
    password = "xxx"
    if os.access(f_path, os.X_OK):
        # 实例化操作类
        myssh = SSHUtils(ipaddr, user_name, password)
        # 停止程序和删除旧jar包
        ret = myssh.exec_command(stop_cmd)
        print(ret)
        # 上传新jar包
        myssh.upload(f_path, o_file_path)
        # 启动程序
        ret = myssh.exec_ssh_command(start_cmd)
        print(ret)
    else:
        print("jar包不存在,请先打jar包后再执行...")
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值