python多线程远程ssh连接 执行命令

使用paramiko进行ssh连接,同时threading进行多线程处理

 threads = []
            for item in array:
                t = threading.Thread(target = self.verifySingle_account, args = (allSshInfo, username, password, port, item))
                threads.append(t)
            for thr in threads:
                thr.start()
            for thr in threads:
                """
                isAlive()方法可以返回True或False,用来判断是否还有没有运行结束
                的线程。如果有的话就让主线程等待线程结束之后最后再结束。
                """
                if thr.isAlive():
                    thr.join()

def verifySingle_account(self, allInfo, username, password, port, item):
        try:
            #创建一个ssh的客户端,用来连接服务器
            ssh = paramiko.SSHClient()
            #创建一个ssh的白名单
            know_host = paramiko.AutoAddPolicy()
            #加载创建的白名单
            ssh.set_missing_host_key_policy(know_host)
            ssh.connect(
                hostname = item["name"],
                port = port,
                username = username,
                password = password,
                timeout = 5
            )
        except Exception as e:
           
        else:
            ssh.close()

ssh连接后 进行执行命令。
同时此处有个问题,命令执行结束但未发生错误时,stdout不能进行read()或readlines,可能会一直卡住,因为程序认为没有执行完,会一直进行等待读取后续的,但是其实后续已经没有了,所以等到超时会直接报错,
所以在此处我进行了stdout的readline,如果找到成功时的输出便便关闭连接,处理下面的程序。

          stdin, stdout, stderr = ssh.exec_command(deploy_command)
            out = ''
            is_success = False
            while True:
                temp = stdout.readline()
                if not temp:
                    break
                out = out + temp
                if (out.find('成功时的输出') != -1):
                    ssh.close()
                    is_success = True
            err = stderr.read()
            ssh.close()
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风吹过你怎么样了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值