最近在学习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,求指教。
The problem lies in the following sentence:
The Thread constructor will not perform a deep copy of the args parameters, and will only be used when starting.
But when your program starts, self.host and self.port have been assigned to the last host and port at the end of the loop,
So once the threads are started, the last host is accessed.
The solution is not to share a variable. Here is a modification:
Other places can also be modified accordingly.