1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import time from netmiko import ConnectHandler, NetMikoAuthenticationException, NetMikoTimeoutException import os import re
time_str1 = time.strftime('%Y_%m_%d', time.localtime()) time_str2 = time.strftime('%H%M%S', time.localtime()) time_str3 = time.strftime('%H:%M:%S', time.localtime()) path = "F:\\XXXXX\\py_net" title = "%s" % time_str1
new_path = os.path.join(path, title) config_path = "%s\\configuration_backup" % new_path if not os.path.isdir(new_path): os.makedirs(new_path) if not os.path.isdir(config_path): os.makedirs(config_path)
log_fo = open('%s\\%s.log' % (config_path, time_str1), 'a+', encoding='utf-8') log_fo.write('\n' + "==========START TIME " + time_str3 + "=========" + '\n')
ip_list = open('ip_list.txt', 'r', encoding='ascii') ip_addr = ip_list.readlines() ip_list.close()
cmd_list = open('cmd_list.txt', 'r', encoding='ascii') cmd_line = cmd_list.readlines() cmd_list.close()
for ip in iter(ip_addr): try: S5130 = { 'device_type': 'hp_comware', 'ip': ip, 'username': 'admin', 'password': 'xxxxxxxxxx', }
net_connect = ConnectHandler(**S5130) screen_d = net_connect.send_command('screen-length disable') time_str2 = time.strftime('%H%M%S', time.localtime()) sysn = net_connect.send_command('dis cur | inc sysname') sysn = re.split(r'[ ]+', sysn) sysn = sysn[2] config_fo = open('%s\\%s_%s_config.txt' % (config_path, sysn, time_str2), 'a', encoding='utf-8') time_str3 = time.strftime('%H:%M:%S', time.localtime()) print(time_str1 + "_" + time_str3 + ' Successfully connected to ' + ip) log_fo.write(time_str1 + "_" + time_str3 + ' Successfully connected to ' + ip) for cmd in iter(cmd_line): cmd_result = net_connect.send_command(cmd) print(cmd) print(cmd_result) print('===================================================================') config_fo.write('\n' + '===================================================================' + '\n' + cmd + '\n' + cmd_result) net_connect.disconnect() config_fo.close() except (EOFError, NetMikoTimeoutException): print('Can not connect to Device ' + ip) time_str3 = time.strftime('%H:%M:%S', time.localtime()) log_fo.write(time_str1 + "_" + time_str3 + ' Can not connect to Device ' + ip) except (EOFError, NetMikoAuthenticationException): print('username/password wrong! ' + ip) time_str3 = time.strftime('%H:%M:%S', time.localtime()) log_fo.write(time_str1 + "_" + time_str3 + ' username/password wrong! ' + ip) time_str4 = time.strftime('%H:%M:%S', time.localtime()) log_fo.write('\n' + "==========END TIME " + time_str4 + "==========" + '\n') log_fo.close() print(log_fo)
|