python多线程并发
# coding=utf8
# 使用前需安装net-snmp-utils或net-snmp包
from _utils.patrol2 import run_cmd
import sys
import os
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
from zipfile import ZipFile
import stat
import time
import datetime now_time = datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S') # def get_host_ip():
# try:
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# s.connect(('8.8.8.8', 80))
# ip = s.getsockname()[0]
# finally:
# s.close()
# return ip
#
# ftp_ips = get_host_ip()
# if ftp_ips in (None,'') or ftp_ips.startswith('127.'):
#
# print 'ftp_ip:',ftp_ip def get_type(host):
cmd = 'snmpwalk -v {} -c {} {}|head -1'.format(snmp_version, community, host)
# print cmd
code, result = run_cmd(cmd)
if code:
print '查询类型失败'
sys.exit(1)
# print result
if 'H3C' in result:
return 'H3C'
else:
return 'Cisco' def snmp_set(host, oid):
cmd = 'snmpset -r 0 -v {} -c {} {} {}'.format(snmp_version, community, host, oid)
# print cmd
code, result = run_cmd(cmd)
return code, result def snmp_test(pre_oid, host, flag):
cmd = 'snmpwalk -r 0 -v {} -c {} {} {}.{}'.format(snmp_version, community, host, pre_oid, flag)
# print cmd
code, result = run_cmd(cmd)
return code, result def do_snmp(host, filename, ftp_ip):
if connect_type != 'tftp' and (not username or not password):
print '文件服务器的登录用户名或密码缺失,请重新输入后尝试'
sys.exit(1) device_type = get_type(host)
print device_type
if device_type == 'H3C':
pre_oid = '1.3.6.1.4.1.25506.2.4.1.2.4.1.9'
elif device_type == 'Cisco':
pre_oid = '.1.3.6.1.4.1.9.9.96.1.1.1.1.3' flag_num = 1
while 1:
code, res = snmp_test(pre_oid, host, flag_num)
if (code and res) or 'No Such Instance currently exists at this OID' in res:
break
flag_num += 1 if device_type == 'H3C':
action_type = '1.3.6.1.4.1.25506.2.4.1.2.4.1.2.{} i 3'.format(
flag_num) # 指定配置文件操作类型,3为当前系统运行的配置
filename = '1.3.6.1.4.1.25506.2.4.1.2.4.1.4.{} s {}'.format(flag_num,
filename) # 指定文件名,目的文件名
ftp_ip = '1.3.6.1.4.1.25506.2.4.1.2.4.1.5.{} a {}'.format(flag_num, ftp_ip) # 指定服务器地址
if connect_type == 'tftp':
protocol_type = '1.3.6.1.4.1.25506.2.4.1.2.4.1.3.{} i 2'.format(flag_num) # 2 #使用TFTP协议
elif connect_type == 'ftp': # 1 #使用FTP协议
login_info = '1.3.6.1.4.1.25506.2.4.1.2.4.1.6.{flag_num} s {username} 1.3.6.1.4.1.25506.2.4.1.2.4.1.7.{flag_num} s {password} '.format(
username=username, password=password, flag_num=flag_num)
ftp_ip = ftp_ip + ' ' + login_info
protocol_type = '1.3.6.1.4.1.25506.2.4.1.2.4.1.3.{} i 1'.format(flag_num) # 1 #使用FTP协议 save_log = '1.3.6.1.4.1.25506.2.4.1.2.4.1.9.{} i 4'.format(flag_num)
oid = '{action_type} {protocol_type} {filename} {ftp_ip} {save_log}'.format(
action_type=action_type, filename=filename, protocol_type=protocol_type, ftp_ip=ftp_ip,
save_log=save_log)
elif device_type == 'Cisco':
action_type = '.1.3.6.1.4.1.9.9.96.1.1.1.1.3.{} i 4'.format(
flag_num) # 指定配置文件操作类型,3为当前系统运行的配置
filename = '.1.3.6.1.4.1.9.9.96.1.1.1.1.6.{} s "{}"'.format(flag_num, filename) # 指定文件名
ftp_ip = '.1.3.6.1.4.1.9.9.96.1.1.1.1.5.{} a {}'.format(flag_num, ftp_ip) # 指定服务器地址
if connect_type == 'tftp':
protocol_type = '.1.3.6.1.4.1.9.9.96.1.1.1.1.4.{} i 1'.format(flag_num) # 2 #使用TFTP协议
elif connect_type == 'ftp': # 1 #使用FTP协议
protocol_type == ''
save_log = '.1.3.6.1.4.1.9.9.96.1.1.1.1.14.{} i 4'.format(flag_num)
oid = '{action_type} {protocol_type} {ftp_ip} {filename} {save_log}'.format(
action_type=action_type, filename=filename, protocol_type=protocol_type, ftp_ip=ftp_ip,
save_log=save_log)
print oid
code, res = snmp_set(host, oid)
if code:
print '{}配置备份失败'.format(host)
print res
return False,filename,ftp_ip
else:
print '{}配置备份成功'.format(host)
time.sleep(2)
# print res
return True,filename,ftp_ip def zip_file(filenames):
has_file = False
dest_path = os.path.join(ftp_directory, '{}.zip'.format(now_time)) for path in filenames:
if not os.path.exists(path):
print '{}文件不存在'.format(path)
filename = path.split(os.sep)[-1]
failhosts.append(filename.split('_')[0])
continue
run_cmd('chmod 777 {}'.format(path))
dest_path = '{}/{}.zip'.format(ftp_directory, now_time)
code, res = run_cmd('tar -rvf {} {}'.format(dest_path, path))
if not code:
has_file = True
os.remove(path)
else:
failhosts.append(path.split('_')[0])
print res
# filename = path.split(os.sep)[-1]
# print path, filename
# with ZipFile(dest_path, mode='a') as fp:
# fp.write(path, filename)
if has_file:
return dest_path
else:
return 'no back files' def get_result(status):
status,name,host_member = status.result()
if status:
filenames.append(os.path.join(ftp_directory, name))
else:
failhosts.append(host_member) if __name__ == '__main__':
try:
filenames = []
failhosts = []
if host_file not in ([], [''], '', None):
with open(host_file[0], 'r') as f:
hosts = f.readlines()
else:
hosts = host.split(',') p = ProcessPoolExecutor()
for host_member in hosts:
host_member = host_member.strip()
if filename:
name = '{}_{}_{}'.format(host_member, now_time, filename)
else:
name = '{}_{}.cfg'.format(host_member, now_time) res = p.submit(do_snmp, host_member, name, ftp_ip).add_done_callback(get_result) p.shutdown()
if filenames:
backup_file = zip_file(filenames)
print '备份完成,备份文件路径:', backup_file if not filenames:
backup_file = 'no back files'
print '备份失败'
if failhosts:
print '设备备份失败:', ','.join(failhosts)
failhosts = ','.join(failhosts)
if not failhosts:
failhosts='null'
except Exception as e:
print '设备备份失败:', e
上述例子是多进程
下面是多线程
# coding=utf8
from _utils.patrol2 import run_cmd,data_format,report_format
import sys
import os
from concurrent.futures import ThreadPoolExecutor
import time reports=[]
def get_result(status):
global reports
status_res = status.result()
#print status_res
reports.append(status_res)
# if status:
# filenames.append(os.path.join(ftp_directory, name))
# else:
# failhosts.append(host_member) def get_status(ip):
print ip
time.sleep(20)
return 11 if __name__ == '__main__':
try:
ip = [str(i) for i in range(0, 60)]
p = ThreadPoolExecutor(max_workers=50)
for ipaddress in ip:
res = p.submit(get_status,ipaddress).add_done_callback(get_result) p.shutdown()
print reports
except Exception as e:
print '设备备份失败:', e
python多线程并发的更多相关文章
- Python 多线程并发程序设计与分析
多线程并发程序设计与分析 by:授客 QQ:1033553122 1.技术难点分析与总结 难点1:线程运行时,运行顺序不固定 难点2:同一段代码,再不加锁的情况下,可能被多个线程同时执行,这会造成很多 ...
- 用Queue控制python多线程并发数量
python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误. 下面介绍用Queue控制多线程并发数量的方法(python3). # -*- coding: utf ...
- Python多线程并发的误区
由于项目要做一个并发测试,由于断言的东西较多,决定手写脚本.于是用python写了脚本: def test_method(thread_no): print("%s===test_metho ...
- python 多线程并发threading & 任务队列Queue
https://docs.python.org/3.7/library/concurrency.htmlpython程序默认是单线程的,也就是说在前一句语句执行完之前后面的语句不能继续执行先感受一下线 ...
- python 多线程 并发socket实例
sever side: import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self ...
- Python 多线程教程:并发与并行
转载于: https://my.oschina.net/leejun2005/blog/398826 在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global int ...
- python多进程并发和多线程并发和协程
为什么需要并发编程? 如果程序中包含I/O操作,程序会有很高的延迟,CPU会处于等待状态,这样会浪费系统资源,浪费时间 1.Python的并发编程分为多进程并发和多线程并发 多进程并发:运行多个独立的 ...
- Python Socket多线程并发
1.SocketServer模块编写的TCP服务器端代码 Socketserver原理图 服务端: import SocketServer #导入SocketServer,多线程并发由此类实现 cla ...
- python 多进程并发与多线程并发
本文对python支持的几种并发方式进行简单的总结. Python支持的并发分为多线程并发与多进程并发(异步IO本文不涉及).概念上来说,多进程并发即运行多个独立的程序,优势在于并发处理的任务都由操作 ...
随机推荐
- 理解maven命令package、install、deploy的联系与区别
我们在用maven构建java项目时,最常用的打包命令有mvn package.mvn install.deploy,这三个命令都可完成打jar包或war(当然也可以是其它形式的包)的功能,但这三个命 ...
- HDU 6425(羽毛球组合 **)
题意是说有四种同学,没有球拍没有球的( a ),只有球拍的( b ),只有球的( c ),既有球拍又有球的( d ):现在要去打羽毛球,每个人都可以选择去或者不去,问有多少种无法打羽毛球的情况. 无法 ...
- STL优先队列
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> usin ...
- cxf与spring的整合
cxf与spring的整合: 一:服务端相关配置(配置好后启动tomocat就自动发布了接口,浏览器打开验证下) 1:导入cxf以及spring的相关jar包; 2:在web.xml中增加配置: 代码 ...
- 自定义类使用泛型and方法使用泛型
使用泛型的自定义类,泛型可以使用任意的数据类型,在创建对象的时候确定是什么数据类型,创建对象的时候不使用泛型,那就默认是Object类型 格式: 使用泛型的自定义类 package cn.zhuobo ...
- Http状态码解释
参考:urllib与urllib2的学习总结(python2.7.X) # Table mapping response codes to messages; entries have the # f ...
- MongoDB 更新数组中的元素
本文记录如何更新MongoDB Collection 中的Array 中的元素.假设Collection中一条记录格式如下: 现要删除scores 数组中,"type" 为 &qu ...
- UDP客户/服务器程序所用的套接字函数
- 二十、Linux 进程与信号---非局部跳转
20.1 setjmp 和 longjmp 函数 20.1.1 函数介绍 #include <setjmp.h> int setjmp(jmp_buf env); 函数功能:设置非局部跳转 ...
- [译]Use Dependency Injection In WebForms Application
怎么在已用的WebForm应用中使用DI 假设有一个电影网站,有个页面会列出最近热门的电影.这个项目中使用了仓储模式来获取数据. public partial class Default : Syst ...