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 相关概念: 线程池可以看做容纳线程的容器: 一个应用程序最多只能有 ...
随机推荐
- 使用node去爬虫
let http = require('http'); let https = require('https');//引入node的https服务. let cheerio = require('ch ...
- java解析Json字符串之懒人大法
面对Java解析Json字符串的需求,有很多开源工具供我们选择,如google的Gson.阿里巴巴的fastJson.在网上能找到大量的文章讲解这些工具的使用方法.我也是参考这些文章封装了自己的Jso ...
- Jenkins之发送html附件邮件配置
邮件配置: 邮件内容范例: ${FILE,path="C:\\Users\\Administrator\\.jenkins\\workspace\\XXX自动化测试工程目录\\$JOB_BA ...
- BZOJ3207花神的嘲讽计划Ⅰ——主席树+hash
题目描述 背景 花神是神,一大癖好就是嘲讽大J,举例如下: “哎你傻不傻的![hqz:大笨J]” “这道题又被J屎过了!!” “J这程序怎么跑这么快!J要逆袭了!” …… 描述 这一天DJ在给吾等众蒟 ...
- BZOJ4650 NOI2016优秀的拆分(后缀数组)
显然只要求出以每个位置开始的AA串数量就可以了,将其和反串同位置的结果乘一下,加起来就是答案.考虑对每种长度的字符串计数.若当前考虑的A串长度为x,我们每隔x个字符设一个关键点,求出相邻两关键点的后缀 ...
- HUD 1024 Max Sum Plus Plus (滚动数组)
题意:从一个序列中选出分成不交叉的m段 的最大和 解析 : 题目中 1 <= n <=1000000 所以二维数组是不能用了 所以 要想到简化为一维 dp[i][j]表示以i结尾的前i个 ...
- Studio启动的时候报错 Could not install Gradle distribution from
安装了studio以后,直接点击[Start]报如下错,绝对不是网络的问题. Could not install Gradle distribution from 'https://services. ...
- 【POI每日题解 #6】KRA-The Disks
题目链接 : [POI2006]KRA-The Disks 好有既视感啊... 注意一下输入输出 输入是从上到下输入箱子的宽度 输出是最上面的积木停在哪一层 即 箱子高度 - 积木高度 + 1 在初始 ...
- 【BZOJ4259】残缺的字符串(FFT)
[BZOJ4259]残缺的字符串(FFT) 题面 给定两个字符串\(|S|,|T|\),两个字符串中都带有通配符. 回答\(T\)在\(S\)中出现的次数. \(|T|,|S|<=300000\ ...
- 【转】cJSON 使用笔记
缘 起 最近在stm32f103上做一个智能家居的项目,其中选择的实时操作系统是 rt_thread OS v1.2.2稳定版本,其中涉及到C和java(android)端数据 ...