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本文不涉及).概念上来说,多进程并发即运行多个独立的程序,优势在于并发处理的任务都由操作 ...
随机推荐
- C++ Random 的使用
1.rand() 方法 rand()不需要参数,它会返回一个从0到最大随机数的任意整数,最大随机数的大小通常是固定的一个大整数. 这样,如果你要产生0~10的10个整数,可以表达为: int N ...
- CentOS7 下编译 Hadoop
准备工作 下载 Hadoop 源码 Source (当前最新 2.9.2) https://hadoop.apache.org/releases.html 打开压缩包会看到 BUILDING.txt ...
- python socket原理 及socket如何使(tcp udp协议)
网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. 建立网络通信连接至少要一对端口号(socket).socket本质是编程接口(API) 主要内容: 1.基于 ...
- python 小数据池 is和 == 编码解码
########################总结######################### 今日主要内容 1. 小数据池, id() 小数据池针对的是: int, str, bool 在p ...
- ruby----%使用法
%{String} 用于创建一个使用双引号括起来的字符串,这个表示法与%Q{String}完全一样 result = %{hello} puts "result is: #{result} ...
- 054、准备 macvlan环境(2019-03-21 周四)
参考https://www.cnblogs.com/CloudMan6/p/7352620.html 除了overlay,docker还开发了另一个支持跨主机容器网络的 driver :macvl ...
- React Native的语法之ES5和ES6
原文地址:http://www.devio.org/2016/08/11/React-Native%E4%B9%8BReact%E9%80%9F%E5%AD%A6%E6%95%99%E7%A8%8B- ...
- springboot(十八):CORS方式实现跨域
资料 https://www.cnblogs.com/toutou/p/9843588.html
- 腾讯云cos封装
public class CosUtil { int _appId = xxxxx; string _secretId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ...
- spring注解第01课 @Configuration、@Bean
一.原始的 xml配置方式 1.Spring pom 依赖 <dependency> <groupId>org.springframework</groupId> ...