# 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. Hadoop问题:Input path does not exist: hdfs://Master:9000/user/hadoop/input

    问题描述: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs:/ ...

  2. testlink for windows 安装

    testlink的使用说明可到官网查看:http://www.testlink.org.cn/509.html 一.安装xampp 到xampp官网中下载安装文件,按步骤安装即可. 二.Testlin ...

  3. Eclipse xml中自动提示,添加 dtd或xsd依赖

    下载DTD或XSD文件 添加到Eclipse

  4. windows 中查找占用某个端口的进程并杀死的命令

    如图所示

  5. js中html拼接

    https://i.cnblogs.com/EditPosts.aspx?postid=10620765&update=1

  6. Shell编程(五)脚本语法

    ${}: 数据“内容”删除,替换:{}: 列表 1. 条件测试: test =~:正则匹配 2. if/then/elif/else/fi #!/bin/bash echo "Is it o ...

  7. Golang入门教程(四)变量声明

    Go 语言变量名由字母.数字.下划线组成,其中首个字母不能为数字. 一.Go的语言结构 1.Go的语言基础部分由这几个部分组成 包声明 引入包 函数 变量 语句&表达式 注释 比如下面这个简单 ...

  8. Spark源码剖析 - SparkContext的初始化(三)_创建并初始化Spark UI

    3. 创建并初始化Spark UI 任何系统都需要提供监控功能,用浏览器能访问具有样式及布局并提供丰富监控数据的页面无疑是一种简单.高效的方式.SparkUI就是这样的服务. 在大型分布式系统中,采用 ...

  9. vue基于组件实现简单的todolist

    把todolist拆分为header.footer.list三个模块 index文件 <!DOCTYPE html> <html lang="en"> &l ...

  10. plsql developer 11 + Oracle 11g 开发环境setup

    这是一个很水的博客, 介绍搭建plsql developer 11+ Oracle 11g 开发环境. 1. 本机上安装Oracle 11g express 对于开发足够了, 300MB的下载文件, ...