交換機故障自愈
阿新 • • 發佈:2020-08-05
# -*- coding: UTF-8 -*- """ auto: huangfz """ import telnetlib import time def connect(ip, username, password, command): # tn = telnetlib.Telnet(ip.encode('ascii')) tn.read_until(b'Username:') # 使用者名稱 tn.write(username.encode('ascii') + b'\n') tn.read_until(b'Password:') # 密碼 tn.write(password.encode('ascii') + b'\n') if tn.read_until(b'>').decode('utf-8'): print('登入成功') else: print("登入失敗") return tn def get_error(ip, username, password, command, X_value, Y_value): ret_list = [] # 查詢結果 只含有% tn = connect(ip, username, password, command) print("開始執行查詢") tn.write(b'dis int b\n') time.sleep(5) strs = tn.read_very_eager().decode('utf-8') for i in strs.splitlines(): if '%' in i: ret_list.append(i) switch_value = {} # 生成埠名和值 if ret_list: for i in ret_list: switch_value[i.split()[0]] = i.split()[4] # print(switch_value)switch_name_error_X = [] switch_name_error_Y = [] for k, i in switch_value.items(): if int(float(i.split("%")[0])) > int(X_value): switch_name_error_X.append(k) continue if int(float(i.split("%")[0])) < int(X_value) and int(float(i.split("%")[0])) > int(Y_value): switch_name_error_Y.append(k) continue else: print("埠:%s 檢查正常當前為:%s" % (k, i)) print("當前異常埠大於{},埠號為{}".format(X_value, switch_name_error_X)) print("當前異常埠大於{}小於{},埠號為{}".format(Y_value, X_value, switch_name_error_Y)) file_errorX = '' #成需要重啟的命令檔案 file_errorY = '' if len(switch_name_error_X) > 0: starX = 'shutdown' #file_errorX = '' # 生成需要重啟的命令檔案 for i in switch_name_error_X: ret_errorX = '%s\n%s\n' % (i, starX) file_errorX += ret_errorX if len(switch_name_error_Y) > 0: #ret_errorY = '' starY = 'undo shutdown' for i in switch_name_error_Y: ret_errorY = '%s\n%s\n' % (i, starY) file_errorY += ret_errorY if len(file_errorX) > 0 or len(file_errorY) > 0: return True, file_errorX, file_errorY else: return False, "正常" def switch_restart(ip, username, password, command, X_value, Y_value): tn = connect(ip, username, password, command) tn.write(b'sys\n') # 進入sys 模式 while True: ret = get_error(ip, username, password, command, X_value, Y_value) if ret[0]: print("埠異常,開始啟動") #file_errorX if ret[1]:# 執行 shutdown for i in ret[1].splitlines(): tn.write(b'%s\n'%i) time.sleep(0.30) #file_errorX if ret[2]: # 執行 undo shutdown 命令 for j in ret[2].splitlines(): tn.write(b'%s\n'%j) time.sleep(0.30) else: print("當前埠全部正常") break if __name__ == '__main__': command = b'dis int b' # 執行的命令 Username = 'test' # 使用者名稱 Password = 'test' # 密碼 ip = '59.63.188.194' # IP地址 X_value = 90 # X 值 執行 shutdown 命令 Y_value = 80 # Y 值 執行 undo shutdown 命令 switch_restart(ip, Username, Password, command, X_value, Y_value)