Python 简单的多线程执行命令

Tools.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/python
#coding:utf-8
import  threading
import  subprocess
import  os
import  sys
sshport  =  13131
log_path  =  'update_log'
output  =  {}
def  execute(s, ip, cmd, log_path_today):
     with s:     
         cmd  =  '''ssh -p%s root@%s -n "%s" '''  %  (sshport, ip, cmd)
         ret  =  subprocess.Popen(cmd, shell = True , stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
         output[ip]  =  ret.stdout.readlines()
if  __name__  = =  "__main__" :
     if  len (sys.argv) ! =  3 :
         print  "Usage: %s config.ini cmd"  %  sys.argv[ 0 ]
         sys.exit( 1 )
                                      
     if  not  os.path.isfile(sys.argv[ 1 ]):
         print  "Usage: %s is not file!"  %  sys.argv[ 1 ]
         sys.exit( 1 )
                                          
     cmd  =  sys.argv[ 2 ]
                                      
     =  open (sys.argv[ 1 ], 'r' )
     list  =  f.readlines()
     f.close()
     today  =  datetime.date.today()
     log_path_today  =  '%s/%s'  %  (log_path,today)
     if  not  os.path.isdir(log_path_today):
         os.makedirs(log_path_today)
                                      
     threading_num  =  100
     if  threading_num >  len ( list ):
         threading_num  =  len ( list )
     =  threading.Semaphore(threading_num)
                                      
     for  line  in  list :
         ip  =  line.strip()
         =  threading.Thread(target = execute,args = (s, ip,cmd,log_path_today))
         t.setDaemon( True )
         t.start()
                                          
     main_thread  =  threading.currentThread()
     for  in  threading. enumerate ():
         if  is  main_thread:
             continue
         t.join()
                                          
     for  ip,result  in  output.items():
         print  "%s: "  %  ip
         for  line  in  result:
             print  "    %s"  %  line.strip()
                                      
     print  "Done!"


脚本读取两个参数,第一个为存放IP的文本,第二个为shell命令

效果如下:144632398.png


够简单的哈。。。直接调用ssh。。

本文转自运维笔记博客51CTO博客,原文链接http://blog.51cto.com/lihuipeng/1321655如需转载请自行联系原作者


lihuipeng

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值