利用Pool类多进程实现批量主机管理

 #!/usr/bin/python
# -*- coding: UTF-8 -*-
# Author: standby
# Time: 2017-03-02
# Description: Achieve the Multiple Processes(High Concurrent) to execute single or multiple commands functions by pool class of Python Lang. import time
import commands, subprocess
import os, re, sys
import paramiko
from multiprocessing import Pool # print color
COLOR_PINK = '\033[95m'
COLOR_BLUE = '\033[94m'
COLOR_GREEN = '\033[92m'
COLOR_YELLOW = '\033[93m'
COLOR_RED = '\033[91m'
COLOR_DEFAULT = '\033[0m' def Check_IP(ip):
ip_str = r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
if re.match(ip_str, ip):
return True
else:
return False def Get_IPS(ipfile):
'''Generate ip list.'''
ips = []
with open(ipfile) as iplist:
content = iplist.readlines()
for line in content:
if line.startswith('#'):
continue
elif Check_IP(line.strip('\n')):
ips.append(line.strip('\n'))
else:
print '%s is invalid ip address!' % line.strip('\n')
continue
return ips def concurrentFunc(ip, cmd):
'''single cmd to exec...'''
#RET = subprocess.check_output("ssh root@%s 2> /dev/null cmd" % ip, shell = True)
#status, output = commands.getstatusoutput("ssh root@%s 2> /dev/null cmd" % ip)
#status, output = commands.getstatusoutput("ssh root@%s 2> /dev/null cmd
" % ip)
#return ip+": "+output+", status: "+bytes(status)
#return ip+": "+RET
'''multiple cmd to exec...'''
PORT = 22
USER = "root"
KEY = "/path/known_hosts"
ssh = paramiko.SSHClient()
try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, PORT, USER, KEY, timeout=10)
except paramiko.AuthenticationException:
print ip+" ssh timeout, continue..."
return "SSH ERROR, exit..."
output = []
output.append(ip)
for m in cmd:
stdin, stdout, stderr = ssh.exec_command(m)
output.append(stdout.readlines())
return output def callBackFunc(ret):
print "This is callback func of %s" % ret[0] def output(res_list):
print "%s=================RESULT====================%s" % (COLOR_GREEN, COLOR_DEFAULT)
for res in res_list:
try:
print res.get()[0] + " -> " + ''.join(res.get()[1])
except Exception, e:
print "%sOUTPUT ERROR: %s %s" % (COLOR_YELLOW, e, COLOR_DEFAULT)
continue if __name__ == '__main__':
ipfile = sys.argv[1]
if os.path.isfile(ipfile):
ips = Get_IPS(ipfile)
elif Check_IP(ipfile):
ips = [sys.argv[1]]
else:
print '%s is invalid ip address!' % ipfile
sys.exit(1) res_list = []
#cmd = ['cmd1', 'cmd2']
cmd = ['cmd']
t_start=time.time()
#pool = Pool(32)
pool = Pool(10)
for ip in ips:
#维持执行的进程总数为processes,当一个进程执行完毕后会添加新的进程进去
res = pool.apply_async(func=concurrentFunc, args=(ip, cmd,), callback=callBackFunc)
res_list.append(res)
pool.close()
pool.join()
pool.terminate()
output(res_list)
t_end=time.time()
t=t_end-t_start
print '%sDealt %d, used time is :%s.%s' % (COLOR_BLUE, len(res_list), t, COLOR_DEFAULT)

Pool多进程示例的更多相关文章

  1. Python异常处理和进程线程-day09

    写在前面 上课第九天,打卡: 最坏的结果,不过是大器晚成: 一.异常处理 - 1.语法错误导致的异常 - 这种错误,根本过不了python解释器的语法检测,必须在程序运行前就修正: - 2.逻辑上的异 ...

  2. python多线程与多进程--存活主机ping扫描以及爬取股票价格

    python多线程与多进程 多线程: 案例:扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活) 普通版本: #扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活)im ...

  3. boost::pool 库速记

    使用示例 #include <functional> #include <iostream> #include <boost/pool/pool.hpp> #inc ...

  4. php多进程编程实现与优化

    PHP多进程API 创建子进程 @params void @returns int int pcntl_fork(void) 成功时,在父进程执行线程内返回产生的子进程PID,在子进程执行线程内返回0 ...

  5. Python的Multiprocessing多进程实例

    最近在拜读RBG大神的faster-rcnn源码时发现他用了多进程去分阶段处理神经网络,原因如下: # ------------------------------------------------ ...

  6. 笔记-python-standard library-17.2 multiprocessing

    笔记-python-standard library-17.2 multiprocessing 1.      multiprocessing source code:Lib/multiprocess ...

  7. 使用 multiprocessing.dummy 执行多线程任务

    # -*- coding: utf-8 -*- # from multiprocessing import Pool 多进程 from multiprocessing.dummy import Poo ...

  8. ThreadPool 线程池的作用

    相关概念: 线程池可以看做容纳线程的容器: 一个应用程序最多只能有一个线程池: ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池: 每排入一个工作函数,就相 ...

  9. 浅谈ThreadPool 线程池

    本文来自:http://www.cnblogs.com/xugang/archive/2010/04/20/1716042.html 相关概念: 线程池可以看做容纳线程的容器: 一个应用程序最多只能有 ...

随机推荐

  1. Centos7 yum安装Chrome浏览器

    一.创建yum源文件 cd /etc/yum.repo.d/ touch google-chrome.repo 二.输入yum源信息 [google-chrome] name=google-chrom ...

  2. 【转帖】M1、M2增速

    M1.M2增速的背离与广义财政的资金滞留有关 作者: 万钊 2016-07-19 17:20 近期M1.M2增速的背离,引起了各方的极大关注.我们知道,M1以活期存款为主,具有高波动性,其增速与M2背 ...

  3. 使用highlightjs自定义markdown代码高亮

    目录 概述 实现方法 概述 最近使用markdown来写一些技术文档和博客,觉得真心不错,这才是程序员该用的编辑器嘛~~ Mou在mac上的 markdown 编辑器,很简约,可惜Mou好像只支持标准 ...

  4. 自定义控件DataPager

    在最近的一个项目中,涉及到一个自定义翻页控制的控件,下面就这一个控件做详细的说明,这个自定义控件的主要作用是对数据源进行翻页控制,比如说:“上一页.下一页.首页.末页”等相关操作,由于在一个项目中有多 ...

  5. 【Java】 枚举类

    如果要定义一个枚举类: public enum Size { SAMLL, MEDIUM, LARGE, EXTRA, EXTRA_LARGE}; 实际上,这个声明定义的类型是一个类,它刚好有4个实例 ...

  6. Json数组对象取值

    1.数据格式 {"data":[{"username":"xxx","avatar":"xxx",& ...

  7. hihocoder #1236 Scores (15北京赛区网络赛J) (五维偏序,强制在线,bitset+分块)

    链接:http://hihocoder.com/problemset/problem/1236 思路; 有n个五维的向量,给出q个询问,每个询问是一个五维向量,问有多少个向量没有一维比这个向量大.并且 ...

  8. 分数模板(C++模板)

    貌似没什么用...没有多少毒瘤题要输出分数吧... update:真的有,而且在NOIP模拟赛里出现了!写double的卡精度到怀疑人生! 可以套个兼容性比较好的高精度模板进来. #include&l ...

  9. 自学Zabbix2.4-web页面配置zabbix

    点击返回:自学Zabbix之路 ....

  10. OneProxy 管理

    -----client-----------haproxy---------mysql1----------mysql2------192.168.1.250 192.168.1.1 192.168. ...