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 = [] show_cmd = '\n show ver \n' \ 'show run \n' \ 'show fan \n' \ 'show env all' def 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] secret = list[4].replace('\n', '') # 去除换行符 conn_s = ConnectHandler(device_type=devtype, host=ip, username=admin, password=devpasswd, secret=secret, ) conn_s.enable() time.sleep(1) conn_n = ConnectHandler(device_type=devtype, host=ip, username=admin, password=devpasswd, ) print(f'已成功登陆交换机{hostname}') if devtype == 'hp_comware': output = conn_n.send_command_timing('screen-length disable\n dis cu ') elif devtype == 'huawei_telnet': output = conn_n.send_command_timing('screen-length 0 temporary\n dis cu') elif devtype == 'juniper_junos': output = conn_s.send_command_timing('show configuration | display set | no-more') elif devtype == 'cisco_ios_telnet': # output = conn.send_command_timing('\n terminal length 0 \n show running-config \n show ver \n show env all') output = conn_s.send_command_timing(show_cmd) conn_s.disconnect() conn_n.disconnect() logname = "E:\Python\python_Shell/" + today + "/" + hostname + "_" + today + ".log" time.sleep(2) try: os.mkdir("E:\Python\python_Shell/" + 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) devlist = open('E:/Python/python_Shell/device_pwd.txt', 'r') for line in devlist.readlines(): session(line) for i in switch_with_authentication_issue: print(f" {i}") for i in switch_not_reachable: print(f" {i}")
标签:巡检,show,hostname,list,devtype,自动化,output,网络设备,conn From: https://www.cnblogs.com/dengcongcong/p/16636859.html