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 相关概念: 线程池可以看做容纳线程的容器: 一个应用程序最多只能有 ...
随机推荐
- Jquery 组 表单验证
<!DOCTYPE html><html lang="zh-cn"><head> <meta charset="utf-8&qu ...
- 微信小程序开发4之form表单与弹出层
第一 表单的提交和重置 第二 radio组件 第三 checkbox组件 第四 loading组件 第五 toast组件 第六 modal组件
- BZOJ2819Nim——树链剖分+线段树+Nim游戏
题目描述 著名游戏设计师vfleaking,最近迷上了Nim.普通的Nim游戏为:两个人进行游戏,N堆石子,每回合可以取其中某一堆的任意多个,可以取完,但不可以不取.谁不能取谁输.这个游戏是有必胜策略 ...
- 注册页面手机验证码无跳转接收[html+js+ajax+php]
[学习笔记] 来源:注册时需要使用短信验证码,但是注册的时候,点击接收验证码时,会产生跳转(尼玛,这不是我想要的啊!o(╥﹏╥)o) 查询资料和看书之后,知道使用js+ajax可以实现,就从网上找了一 ...
- [ctsc2018] 混合果汁 【可持久化线段树】【二分答案】
题目分析 首先考虑到最小值最大,二分答案.假设答案为k,显然这满足单调性.如果某个k使得这个情况下选不出.那么比k大的一定也选不出,所以二分答案. 接着我们可以贪心,当我们确认了k以后,一定会优先选费 ...
- MT【24】一道五次方程的求根题
解答: 评:一般的五次及以上的多项式方程是无根式解的,只能用计算机去精确到某某位.但是特殊的比如$x^5=1$显然有根式解,本题就是一个不平凡的特殊的例子,这里的代换用于求解三次方程的求根过程是一样的 ...
- 牛客练习赛 小A与最大子段和 解题报告
小A与最大子段和 题意 在一个序列 \(\{a\}\) 里找到一个非空子段 \(\{b\}\), 满足 \(\sum\limits_{i=1}^{|b|}b_i\times i\) 最大 \(n\le ...
- cf860E Arkady and A Nobody-men (树剖)
容易得出,如果我们按照深度一层一层地做,做完一层后,这层某个点的答案就是它的祖先们的子树大小(统计大小时不包括树根) 由于我太菜了不会别的方法,虽然N是5e5的,还是只好用一个树剖(树状数组降常数)水 ...
- suoi37 清点更多船只 (卡空间线段树)
sbw巨佬的卡空间方法,把线段树的叶节点只记到长度为16的区间,然后在叶节点上暴力修改查询,这样点数是$\frac{N}{8}$的,可以过... orz #include<bits/stdc++ ...
- Mysql插入、替换和无视
在现实的生产环境下,通常我们都会遇到这样的应用场景,需要我们更新数据.替换数据,若存在则不操作. insert into表示插入数据,数据库会检查主键,如果出现重复会报错: replace into表 ...