加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python免密远程执行shell

发布时间:2020-12-20 10:40:10 所属栏目:Python 来源:网络整理
导读:使用paramiko库:https://github.com/paramiko/paramiko 简单封装SSH类 import paramikoclass 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 s

使用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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读