栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

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

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/747600.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号