1 Star 0 Fork 5

foxflying/网络设备自动巡检工具

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ljds.py 2.79 KB
一键复制 编辑 原始数据 按行查看 历史
kzds 提交于 2018-03-07 13:48 . 更新 ljds.py
from netmiko import ConnectHandler
import os
import time
LogTime = time.strftime('%Y-%m-%d_%H-%M-%S')
#读取IP地址、用户名、密码。
#DEVICES = []#每台设备的地址、用户名、密码组成字典,所有设备存放在DEVICES列表中
def get_devices_info(path): #参数是配置文件的路径
DEVICES = []
try:
with open(path, 'r') as f:
for line in f:
if line[0] == '#': #忽略注释行
continue
elif len(line) == 1: #忽略空行(len('\n')==1)
continue
else:
info_list = (line.strip().split())
info_dict = {'ip':info_list[0],'username':info_list[1],'password':info_list[2]}
DEVICES.append(info_dict)
return DEVICES
except FileNotFoundError as e:
print('找不到设备的配置文件')
except IndexError as e:
print('设备配置文件内容格式有误')
# ip username password,3个值中间都有1个空格
#读取巡检命令
#CMD中包含所有巡检命令,以列表的形式存放
def get_cmd_info(path):
CMD = []
try:
with open(path, 'r') as f:
for line in f:
if line[0] == '#': #忽略注释行
continue
elif len(line) == 1: #忽略空行(len('\n')==1)
continue
else:
CMD.append(line.strip())
return CMD
except FileNotFoundError as e:
print('找不到设备的配置文件')
##执行巡检命令
def run_cmd(hosts=get_devices_info('DEVICES.cfg'),commands=get_cmd_info('CMD.cfg')):
# print(hosts)
# print(commands)
if os.path.exists('fail.txt') == True:#先清除巡检失败记录
os.remove('fail.txt')
for i in hosts:
try:
net_connect = ConnectHandler(device_type='cisco_ios',**i)
current_ip = i['ip']
#创建以设备名+时间为文件夹名的目录
dirname = current_ip + '_' + LogTime
os.mkdir(dirname)
for j in commands:
output = net_connect.send_command(j)
time.sleep(1)#等待1秒
with open(dirname+'\\'+j+'.txt', "w") as f:
f.write(output)
print('{}设备完成巡检'.format(i['ip']))
except:
print('{}设备巡检失败,记录保存在当前目录中的fail.txt'.format(i['ip']))
with open('fail.txt', "a") as f:
f.write(i['ip']+'\n')
if __name__=='__main__':
run_cmd()#默认根据cfg文件内容(IP、巡检命令)巡检
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/foxflying/automatic_inspection_tool_for_cisco_equipment.git
git@gitee.com:foxflying/automatic_inspection_tool_for_cisco_equipment.git
foxflying
automatic_inspection_tool_for_cisco_equipment
网络设备自动巡检工具
master

搜索帮助