首页 > 编程语言 > 详细

python 通过threading多线程ssh

时间:2014-08-26 19:54:27      阅读:440      评论:0      收藏:0      [点我收藏+]

#!/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

本文出自 “我是一只小小鸟” 博客,请务必保留此出处http://2242558.blog.51cto.com/2232558/1545306

python 通过threading多线程ssh

原文:http://2242558.blog.51cto.com/2232558/1545306

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!