前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 通过threading多线

python 通过threading多线

作者头像
py3study
发布2020-01-08 16:41:58
8410
发布2020-01-08 16:41:58
举报
文章被收录于专栏:python3

#!/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(src,linerange):      i = 0     for line in open(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,src):     global count, mutex     linesum = sum(1 for line in open(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=(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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档