python 通过threading多线

发布时间:2019-09-08 09:13:28编辑:auto阅读(1499)

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

关键字