# coding=gb2312
import configparser
import os
import time
from netmiko import ConnectHandler
import datetime
from GAOJIN import gaojin
from LOGS import log
# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')
def swbeifen ():
target_value = '交换机'
date1 = datetime.datetime.now().strftime("%Y_%m_%d~%H:%M")
date = datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M")
for section in config.sections():
for key, value in config.items(section):
if value == target_value:
switch_ip = config[section]['ip']
switch_vendor = config[section]['vendor']
switch_username = config[section]['username']
switch_password = config[section]['password']
switch_diqu = config[section]['diqu']
switch_lujing = config[section]['luj']
switch_pinp = config[section]['type']
# 根据厂商选择连接信息和备份命令
if switch_vendor == '思科':
device_info = {
'device_type': 'cisco_ios',
'ip': switch_ip,
'username': switch_username,
'password': switch_password,
}
typewj = "cfg"
backup_command = 'show running-config'
elif switch_vendor == '华为':
device_info = {
'device_type': 'huawei_vrpv8',
'ip': switch_ip,
'username': switch_username,
'password': switch_password,
}
typewj = "txt"
backup_command = 'display current-configuration'
elif switch_vendor == '华三':
device_info = {
'device_type': 'hp_comware',
'ip': switch_ip,
'username': switch_username,
'password': switch_password,
}
typewj = "cfg"
backup_command = 'display current-configuration'
elif switch_vendor == 'aruba':
device_info = {
'device_type': 'hp_procurve',
'ip': switch_ip,
'username': switch_username,
'password': switch_password,
}
typewj = "cfg"
backup_command = 'show running-config'
try:
# 尝试连接交换机
net_connect = ConnectHandler(**device_info)
except Exception as e:
date2 = datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M")
mizi = section
dq = switch_diqu
shibai = (f"网络设备自动备份日志!!!\n"\
f"主机:{mizi}-{switch_ip}\n"\
f"IP:{switch_ip}\n"\
f"地区:{dq}\n"\
f"设备类型:{switch_vendor}{switch_pinp}\n"\
f"时间:{date2}\n"\
f"信息:无法连接设备\n"\
f"问题详情:"+str(e))
log.logs(rizi=str(shibai))
print(shibai)
else:
print(f"已成功连接到{target_value}:",switch_ip)
net_connect.disconnect()
with ConnectHandler(**device_info) as conn:
output = conn.send_command(backup_command)
# 创建以节点名称命名的文件夹到指定目录下,并将备份配置放入其中
folder_name = section
lujing = switch_lujing
backup_folder = os.path.join(lujing,folder_name)
if not os.path.exists(backup_folder):
os.makedirs(backup_folder)
backup_file = os.path.join(backup_folder, f"{folder_name}{date1}.{typewj}")
with open(backup_file, "w") as f:
f.write(output)
date3 = datetime.datetime.now().strftime("%Y年%m月%d日 %H:%M")
rizhi = (f"网络设备自动备份日志!!!\n"\
f"时间:{date3}\n"\
f"设备:{folder_name}\n"\
f"地区:{switch_diqu}\n"\
f"设备类型:{switch_vendor}{switch_pinp}\n"\
f"ip地址:{switch_ip} \n"\
f"成功备份至:{backup_file}")
log.logs(rizi=str(rizhi))
print(rizhi)
swbeifen()