jdxyzlh 发表于 2015-12-15 12:28:43

python 多线程小用

时间总是流淌的那么快, 5年前学习python的热情劲头恍如昨日,10年写的python多进程脚本,以后备用



[*]#!/usr/bin/python

[*]#coding:utf-8
[*]import pexpect
[*]from Queue import Queue
[*]from threading import Thread
[*]import time
[*]import sys
[*]
[*]''' just a practise

[*]
[*]'''
[*]
[*]max_threads = 25
[*]queue =Queue()
[*]
[*]def Dssh_Cmd(i,q):
[*]    hello_world = 'Are you sure to continue connecting'
[*]    while True:
[*]      a = q.get()
[*]      child = pexpect.spawn('ssh %s@%s "%s"' %(a[1],a[0],a[3]))
[*]      fout = open('log.txt','a')
[*]      child.logfile = fout
[*]      index = child.expect([hello_world,'password:',pexpect.EOF])
[*]      if index == 0:
[*]            child.sendline('yes')
[*]            index = child.expect([hello_world,'password:',pexpect.EOF])
[*]      elif index == 1:
[*]            child.sendline(a[2])
[*]            index = child.expect(pexpect.EOF)
[*]      elif index == 2:
[*]            child.close()
[*]      print '--host:%s --cmd:%s' % (a[0],a[3])
[*]      print child.before
[*]      q.task_done()
[*]
[*]def main():
[*]    f = open(sys.argv[1],'r')
[*]    for line in f.readlines():
[*]      queue.put(line.strip().split(":"))
[*]
[*]    for t in range(max_threads):
[*]         worker = Thread(target=Dssh_Cmd,args=(t,queue))
[*]         worker.setDaemon(True)
[*]         worker.start()
[*]    print "main Thread waiting....."
[*]    queue.join()
[*]    f.close()
[*]    print "All Of Done"
[*]
[*]if __name__ == "__main__":
[*]    main()
热情保持下去,努力~
页: [1]
查看完整版本: python 多线程小用