python2.7多线程的批量操作远程服务器

#!/usr/bin/env python
#-*- coding:utf-8 -*-
#多线程批量远程执行一条命令
# made in china

import threading
import sys,os
import subprocess

#cmd = sys.argv[2]
ip_list=[]
ip_fail=[]

def subprocess_caller(cmd):
    try:
        p = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
        output, error = p.communicate()
    except OSError, e:
        print 'SUBPROCEEE_CALLER function: execute command failed, message is %s' % e
        return dict(output = [], error = [], code = 1)
    else:
        return dict(output = output, error = error, code = 0)


#cmd
def run_cmd(num,ip):
    cmd = sys.argv[2]
    
    tmp_cmd = "ssh -o ConnectTimeout=3 -o StrictHostKeyChecking=no root@%s 2>/dev/null  \"%s\" "%(ip,cmd.strip())
    res=subprocess_caller(tmp_cmd)
    #print "===================="
    #print "The %s is %s success"%(ip,num)
    #print "===================="
    if res['output'] != '':
       print "\033[1;35m The %s is succeed  \033[0m  \n %s \n"%(ip,res['output'])
    else:
       print "\033[1;31m The %s is failed \040"%(ip)
       ip_fail.append(ip)

#ip
def get_ip():
    ip_file = sys.argv[1]
    input = open(ip_file,'r')

    while True:
       tmp_ip = input.readline()
       if tmp_ip != '':
          #print type(tmp_ip)
          ip_list.append(tmp_ip.strip())
       else:
          break

    input.close()

    #print ip_list

#多线程
def main():

    get_ip()
    threads = []
    nloops = range(len(ip_list))

    for i in nloops:
        t = threading.Thread(target=run_cmd,args=(i, ip_list[i]))
        threads.append(t)

    for i in nloops:
        threads[i].start()

    for i in nloops:
        threads[i].join()
    if len(ip_fail) != 0: 
        print ip_fail


if __name__ == '__main__':
    main()

  

posted @ 2018-01-23 16:25  JvvYou  阅读(488)  评论(0编辑  收藏  举报