Pool多进程示例
利用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多进程示例的更多相关文章
- Python异常处理和进程线程-day09
写在前面 上课第九天,打卡: 最坏的结果,不过是大器晚成: 一.异常处理 - 1.语法错误导致的异常 - 这种错误,根本过不了python解释器的语法检测,必须在程序运行前就修正: - 2.逻辑上的异 ...
- python多线程与多进程--存活主机ping扫描以及爬取股票价格
python多线程与多进程 多线程: 案例:扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活) 普通版本: #扫描给定网络中存活的主机(通过ping来测试,有响应则说明主机存活)im ...
- boost::pool 库速记
使用示例 #include <functional> #include <iostream> #include <boost/pool/pool.hpp> #inc ...
- php多进程编程实现与优化
PHP多进程API 创建子进程 @params void @returns int int pcntl_fork(void) 成功时,在父进程执行线程内返回产生的子进程PID,在子进程执行线程内返回0 ...
- Python的Multiprocessing多进程实例
最近在拜读RBG大神的faster-rcnn源码时发现他用了多进程去分阶段处理神经网络,原因如下: # ------------------------------------------------ ...
- 笔记-python-standard library-17.2 multiprocessing
笔记-python-standard library-17.2 multiprocessing 1. multiprocessing source code:Lib/multiprocess ...
- 使用 multiprocessing.dummy 执行多线程任务
# -*- coding: utf-8 -*- # from multiprocessing import Pool 多进程 from multiprocessing.dummy import Poo ...
- ThreadPool 线程池的作用
相关概念: 线程池可以看做容纳线程的容器: 一个应用程序最多只能有一个线程池: ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池: 每排入一个工作函数,就相 ...
- 浅谈ThreadPool 线程池
本文来自:http://www.cnblogs.com/xugang/archive/2010/04/20/1716042.html 相关概念: 线程池可以看做容纳线程的容器: 一个应用程序最多只能有 ...
随机推荐
- 表格属性和BFC(block framing content)
th和tr都是表示列但是 th有一个居中加粗的效果. 表单是由 : 1表单域:<form name=" " method="get/post" acti ...
- [书摘]HTTPS--From图解HTTP
1. HTTP存在的安全性风险: 1) 通信过程使用明文,容易被窃听 2) 不验证通信方的身份,可能遭遇伪装 3) 不验证通信数据包的完整性,可能遭遇篡改 2. HTTP+加密+认证+完整性保护=H ...
- Qt__主窗口、菜单和工具条(QMainWindow,QMenu,QToolBar)
转自豆子空间 主窗口 Qt的GUI程序有一个常用的顶层窗口,叫做MainWindow.MainWindow继承自QMainWindow.QMainWindow窗口分成几个主要的区域: 最上面是Wind ...
- FICO模块
- jmeter作用域规则
创建测试计划时,会创建一个有序的一系列将要被执行的请求列表,这些请求通常被组织在有序的控制器下 一些控制器会影响包含在它下面的请求顺序 ,这些特殊的控制器可以参考这里:the component re ...
- the project already contains a form or module named pcm001怎麼解決
the project already contains a form or module named pcm001怎麼解決 菜单Project -> Remove from project.. ...
- ActiveMA在CentOS7下的安装
下载:apache-activemq-5.14.0-bin.tar.gz http://activemq.apache.org/activemq-5157-release.html Getting t ...
- std::shared_ptr 和普通指针的转换
相互转化见示例 struct test { int num; string name; }; test* pTest = new test(); std::shared_ptr<test> ...
- std::binary_serach, std::upper_bound以及std::lower_bound
c++二分查找的用法 主要是 std::binary_serach, std::upper_bound以及std::lower_bound 的用法,示例如下: std::vector<int& ...
- ansible系列8-SSH连接和执行性能优化
1. 当你的SSH的版本高于5.6时 我们可以直接修改 /etc/ansible/ansible.cfg里面的参数 ssh_args = -C -o ControlMaster=auto -o Con ...