python 通过threading多线
#!/usr/bin/env python
#coding=utf-8
import paramiko
import time,datetime,threading
def ssh(ip,user,passwd,command):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip,port=16333,username=user,password=passwd)
except paramiko.AuthenticationException:
#print "验证失败,用户名或密码错误."
return 0
except:
#print 'ip',"主机不可达。"
return 2
stdin, stdout, stderr = ssh.exec_command(command)
lines = [line.strip() for line in stdout.readlines()]
data_include_firstline = "".join(lines)
data_no_firstline = "".join(lines[1:])
return data_include_firstline
def sshcmd(class="lazy" data-src,linerange):
i = 0
for line in open(class="lazy" data-src):
i += 1
if i in range(linerange[0],linerange[1]+1):
ip = line.strip()
user = 'root'
port = 16333
passwd = '123qwe'
command = 'hostname'
result = ssh(ip,user,passwd,command)
if result == 0:
result = '验证失败,用户名或密码错误.'
elif result == 2:
result = '主机不可达.'
print i,ip,result
def main(num,class="lazy" data-src):
global count, mutex
linesum = sum(1 for line in open(class="lazy" data-src))
quotient = linesum/num
threads = []
# 创建一个锁
mutex = threading.Lock()
# 先创建线程对象
for k in xrange(1, num+1):
if k == num:
linerange = quotient*(k-1)+1,linesum
else:
linerange = quotient*(k-1)+1,quotient*k
threads.append(threading.Thread(target=sshcmd, args=(class="lazy" data-src,linerange)))
# 启动所有线程
for t in threads:
t.start()
# 主线程中等待所有子线程退出
for t in threads:
t.join()
starttime = datetime.datetime.now()
if __name__ == '__main__':
# 创建10个线程
main(10,'ip.txt')
endtime = datetime.datetime.now()
print "time span",endtime-starttime
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341