python paramiko多线程遇到的问题

查看:209
本文介绍了python paramiko多线程遇到的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

最近在学习python,用python写了个检查ssh存活的脚本。写完后想增加多线程功能,加快效率,可是一直报错,麻烦大神帮我看下到底错在哪了

以下是代码:

#!/usr/bin/python
import os
import string
import paramiko
import traceback
import threading

class SshServerCMD():
    def __init__(self):
        print 'start'
        self.username = 'root'
        self.passwd = '123'
        self.cmd = 'date +%s'
        self.ssh = paramiko.SSHClient()
        self.pass_file = '/opt/scripts/etc/ssh_proxy.conf'
        self.paramiko_log= '/tmp/check_ssh_proxy.log'
        self.threads = []
        HostList = open(self.pass_file)
        for line in HostList.readlines():
            ARAY_line = string.split(line)
            self.host = ARAY_line[0]
            self.port = int(ARAY_line[1])
            self.t = threading.Thread(target = self.Connect,args = (self.host,self.port,self.username,self.passwd))
            self.threads.append(self.t)
        for i in range(10):
            self.threads[i].start()
        for i in range(10):
            self.threads[i].join()
    def Connect(self,host,port,username,passwd):
        # This function is to connect the agent
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        #ssh.load_system_host_keys()  
        paramiko.util.log_to_file(self.paramiko_log)
        try:
            self.ssh.connect(host,port,username,passwd)
        except Exception as e:
            print '\033[31m' + self.host,str(e)  + '\033[0m'
        else:
            self.Cmd()
            self.ssh.close()
    
    def Cmd(self):
        stdin,stdout,stderr = self.ssh.exec_command(self.cmd)
                self.sout = stdout.readlines()
        print '\033[32m' + self.host,str(self.sout) + '\033[0m'

if __name__ == '__main__':
    SshServerCMD()

以下是/opt/scripts/etc/ssh_proxy.conf文件内容

192.168.1.2 4001
192.168.1.3 4002
192.168.1.4 4003
192.168.1.5 4004
192.168.1.6 4005
192.168.1.7 4006
192.168.1.8 4007
192.168.1.9 4008
192.168.1.10 4009
192.168.1.11 4010

报错:
执行脚本后,发现程序不停在尝试ssh 192.168.1.11,也就是文本中所写的最后一行的ip地址,并且全部都是连接失败。在逻辑上我就想不通,就算是连接失败,也应该从第一行ip开始尝试,为什么会从最后一行ip开始ssh呢?并且一直在尝试ssh最后一行ip,求指教。

解决方案

问题出在下面这句:

self.t = threading.Thread(target = self.Connect,args = (self.host,self.port,self.username,self.passwd))

Thread构造函数不会对args参数进行deep copy,并且在start的时候才会真正使用。
可是你的程序在start时self.host和self.port已经在循环最后被赋值为最后一个host和port,
所以一旦线程都启动后,访问的就是最后一个host。
解决办法是不要共享一个变量,如下是一种改法:

for line in HostList.readlines():
    ARAY_line = string.split(line)
    host = ARAY_line[0]
    port = int(ARAY_line[1])
    self.t = threading.Thread(target = self.Connect,args = (host,port,self.username,self.passwd))
    self.threads.append(self.t)

其他地方也可以跟着修改。

这篇关于python paramiko多线程遇到的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆