python多厂商巡检脚本~

python多厂商巡检脚本~,第1张

import netmiko
from netmiko import ConnectHandler
import time
import os

today = time.strftime("%Y-%m-%d", time.localtime())
switch_with_authentication_issue = []  # 存放认证失败的设备信息
switch_not_reachable = []  # 存放网络不通的设备信息

def ssh_session(devlist):  ##定义备份函数
    try:
        list = line.split(",")
        hostname = list[0]
        hostname = str(list[0])
        devtype = list[1]
        ip = list[2]
        admin = list[3]
        devpasswd = list[4].replace('\n','')  #去除换行符
        conn = ConnectHandler(device_type=devtype,
                              host=ip,
                              username=admin,
                              password=devpasswd,
                              )
        time.sleep(1)
        print(f'已成功登陆交换机{hostname}')
        if devtype == 'hp_comware':  ##H3C
            output = conn.send_command_timing('screen-length disable\n dis cu ')
            print(output)  ###测试使用,测试完成后建议注释
        elif devtype == 'huawei': ##华为
            output = conn.send_command_timing('screen-length 0 temporary\n dis cu')
            print(output)  ###测试使用,测试完成后建议注释
        elif devtype == 'juniper_junos': #juniper
            output = conn.send_command_timing('show configuration | display set | no-more')
            print(output)  ###测试使用,测试完成后建议注释
        elif devtype == 'cisco_ios': #cisco
            output = conn.send_command_timing(' terminal length 0 \n show running-config ')
            print(output)  ###测试使用,测试完成后建议注释
        conn.disconnect()
        logname = "D:\pppppppppppppp/config_log/" + today + "/" + hostname + "_" + today + ".log" #定义备份文件名
        time.sleep(2)
        try:  ###创建日期文件夹
            os.mkdir("D:\pppppppppppppp/config_log/" + today + "/")
        except OSError:
            pass
        wr = open(logname, 'a' or 'w')
        wr.write(output)
        wr.close()
    except netmiko.NetmikoAuthenticationException:  ##防止中间某台设备无法登录或不可达等因素导致进程中断
        print(hostname + "用户验证失败!")
        switch_with_authentication_issue.append(ip)
    except netmiko.ssh_exception.NetmikoTimeoutException:
        print(hostname + "目标不可达!")
        switch_not_reachable.append(ip)
#   except paramiko.ssh_exception.AuthenticationException: ###不同品牌设备可能报错不同,自行添加即可
#           print(hostname + "用户验证失败!")
#           switch_with_authentication_issue.append(ip)

devlist = open('D:\pppppppppppppp/devlist.txt', 'r')  # 建议填写全路径,使用crontab可能会出问题
for line in devlist.readlines():   ##循环
   ssh_session(line)

print('\n ====结果输出====')
print('·下列交换机用户验证失败:')
for i in switch_with_authentication_issue:
    print(f"  {i}")

print('·下列交换机不可达:')
for i in switch_not_reachable:
    print(f"  {i}")

需要在根目录下创建devlist.txt文件(作用存放设备的名字、型号、地址、用户名、密码)如:

h3c_sw,hp_comware,1.1.1.10,admin,123123
cisco_sw,cisco_ios,1.1.1.5,admin,123123

需要在根目录下创建文件夹config_log,(作用为存放巡检完设备的配置)

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/916657.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存