微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python免密远程执行shell

使用paramiko库:https://github.com/paramiko/paramiko

简单封装SSH类

import paramiko


class SSH:

    def __init__(self,host,port,user,ssh_key_path,timeout=1800):
        self.host = host
        self.port = port
        self.user = user
        self.ssh_key_path = ssh_key_path
        self.timeout = timeout
        self.connect()

    def connect(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        pkey = paramiko.RSAKey.from_private_key_file(self.ssh_key_path)
        client.connect(hostname=self.host,username=self.user,port=self.port,pkey=pkey,timeout=self.timeout)
        self.client = client

    def exec(self,shell,timeout=1800):
        stdin,stdout,stderr = self.client.exec_command(command=shell,bufsize=1,timeout=timeout)
        while True:
            line = stdout.readline()
            if not line:
                break
            print(line)
        print(stderr.read())
        code = stdout.channel.recv_exit_status()
        return code

    def close(self):
        self.client.close()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐