python服务器批量处理_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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值