# 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多线程并发的更多相关文章

  1. Python 多线程并发程序设计与分析

    多线程并发程序设计与分析 by:授客 QQ:1033553122 1.技术难点分析与总结 难点1:线程运行时,运行顺序不固定 难点2:同一段代码,再不加锁的情况下,可能被多个线程同时执行,这会造成很多 ...

  2. 用Queue控制python多线程并发数量

    python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误. 下面介绍用Queue控制多线程并发数量的方法(python3). # -*- coding: utf ...

  3. Python多线程并发的误区

    由于项目要做一个并发测试,由于断言的东西较多,决定手写脚本.于是用python写了脚本: def test_method(thread_no): print("%s===test_metho ...

  4. python 多线程并发threading & 任务队列Queue

    https://docs.python.org/3.7/library/concurrency.htmlpython程序默认是单线程的,也就是说在前一句语句执行完之前后面的语句不能继续执行先感受一下线 ...

  5. python 多线程 并发socket实例

    sever side: import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): def handle(self ...

  6. Python 多线程教程:并发与并行

    转载于: https://my.oschina.net/leejun2005/blog/398826 在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global int ...

  7. python多进程并发和多线程并发和协程

    为什么需要并发编程? 如果程序中包含I/O操作,程序会有很高的延迟,CPU会处于等待状态,这样会浪费系统资源,浪费时间 1.Python的并发编程分为多进程并发和多线程并发 多进程并发:运行多个独立的 ...

  8. Python Socket多线程并发

    1.SocketServer模块编写的TCP服务器端代码 Socketserver原理图 服务端: import SocketServer #导入SocketServer,多线程并发由此类实现 cla ...

  9. python 多进程并发与多线程并发

    本文对python支持的几种并发方式进行简单的总结. Python支持的并发分为多线程并发与多进程并发(异步IO本文不涉及).概念上来说,多进程并发即运行多个独立的程序,优势在于并发处理的任务都由操作 ...

随机推荐

  1. 【MSSQL】SQL Server 设置用户只能查看并访问特定数据库

    #背景 SQL Server实例上有多个服务商的数据库,每个数据库要由各自的服务商进行维护, 为了限定不同服务商商的维护人员只能访问自己的数据库,且不能看到其他服务商的数据库,现需要给各个服务商商限定 ...

  2. Nlog日志组件简介

    NLog简介 NLog是一个简单灵活的.NET日志记录类库,NLog的API非常类似于log4net,配置方式非常简单.支持多种形式输出日志:文本文件.系统日志.数据库.控制台.邮箱等 1.NLog简 ...

  3. axis 入门【原】

    Call call = (Call) service.createCall();call.setOperationName(new QName("命名空间地址", "方法 ...

  4. HDU - 6357 Hills And Valleys(DP)

    http://acm.hdu.edu.cn/showproblem.php?pid=6357 题意 给一个数值范围为0-9的a数组,可以选择翻转一个区间,问非严格最长上升子序列,以及翻转的区间. 分析 ...

  5. java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap-----commons-ctions版本问题

    今天用到了一系列的第三方jar包,一环扣一环, 记住一个: 倘若你所导入的第三方jar包中的类一直显示未找到,那就是你的路径出问题了, /WEB-INF/lib目录下才是放第三方jar包位置, 但是今 ...

  6. luogu 1966 火柴排队 离散化+逆序对

    题意:找到最小改变对数使a数组的第i大和b数组的第i大相等 则先将a,b,数组编号再排序,则数组显示的就是排名第i的数的编号 再关键一步:c[a[i].id]=b[i].id 实质上就是新建一个数组, ...

  7. js获取网页面的高度和宽度

    网页可见区域宽:document.body.clientWidth网页可见区域高:document.body.clientHeight网页可见区域宽:document.body.offsetWidth ...

  8. html5 area实例

    真实页面效果:就是一张图 html代码: <!DOCTYPE HTML> <html> <style> body{ padding:0px; margin:0px; ...

  9. LOJ #2196「SDOI2014」LIS

    直接退流复杂度好优越啊 LOJ #2196 题意 一段数列,每个点有点权$ A_i$,删除代价$ B_i$,附加属性$ C_i$ 求最小代价使得$ LIS$长度发生变化,且输出一种$ C_i$字典序最 ...

  10. java Object类的公共方法

    1.HashCode();      2. wait();  3. notify(); 4.equals(); 5.getClass(); 6.toString(); 7.clone(); 8.fin ...