import telnetlib
import time
import sys
import os.path
import configparseride
class TelnetClient():
def init(self,):
self.tn = telnetlib.Telnet() # 定義一個Telnet鏈接ui
def Login(self,HostIP,Username,Password): # 給定參數進行鏈接 try: self.tn.open(HostIP,port=23) # 鏈接 self.tn.read_until(b'login: ',timeout=5) # 等待login:出現,最多等待5秒 self.tn.write(Username.encode('ascii') + b'\n') # 輸入用戶名稱 self.tn.read_until(b'Password: ',timeout=5) # 等待Password:出現,最多等待5秒 self.tn.write(Password.encode('ascii') + b'\n') # 輸入用戶口令 time.sleep(2) # 延時兩秒 Result = self.tn.read_very_eager().decode('ascii') # 獲取返回結果 if '<'+Equipmentname+'>' in Result: return True # 成功登錄 else: self.Disconnect() self.StrErr = '鏈接地址:{}失敗,用戶名稱或者密碼錯誤。\r\n'.format(HostIP) return False # 登錄失敗 except: self.StrErr='鏈接地址:{}失敗!\r\n'.format(HostIP) # 異常 self.Disconnect() return False def ExecuteCommand(self,command): # 執行命令 Year = time.strftime('%Y', time.localtime(time.time())) Month = time.strftime('%m', time.localtime(time.time())) Day = time.strftime('%d', time.localtime(time.time())) Pathname, Filename = os.path.split(os.path.abspath(sys.argv[0])) SaveFile = Pathname + "\\" + Equipmentname + Year + Month + Day + ".txt" file_object = open(SaveFile, 'ab+') # 打開文件準備寫 file_object.write(Equipmentname.encode('ascii')+b"\r\n") # 將返回的結果寫入文件 self.tn.write(command.encode('ascii')+b'\n') # 執行命令 time.sleep(1) Result=self.tn.read_very_eager() while True: file_object.write(Result) # 將返回的結果寫入文件 if not Result.find(StrMore.encode('ascii'))>0: break self.tn.write(b" ") # 發送空格鍵 time.sleep(1) Result=self.tn.read_very_eager() def Logout(self): # 正常退出 self.tn.write(b"exit\n") def Disconnect(self): # 異常關閉 self.tn.close()
if name == 'main':
Equipmentname='' # 設備名稱
HostIP = '' # IP地址
Username = '' # 用戶名稱
Password = '' # 密碼
Command = [] # 命令集
CommandPrompt="" # 命令提示符
StrMore="-- More --"
conf = configparser.ConfigParser() # 定義一個讀取對象
conf.read("NetConfig.ini") # 打開配置文件
sections = conf.sections() # 返回全部的section,列表
NewTelnetClient = TelnetClient() # 實例化
for section in sections:spa
HostIP=section Equipmentname=conf.get(section, 'EquipmentName') Username=conf.get(section, 'Username') Password=conf.get(section, 'Password') Command=conf.get(section, 'CommandSet') Command=conf.get(section, 'CommandSet').split(',') if NewTelnetClient.Login(HostIP, Username, Password): # 若是正常登陸則執行命令,完成後退出 print("設備:{},IP地址:{}".format(Equipmentname, HostIP)) for S in Command: print("執行:",S) NewTelnetClient.ExecuteCommand(S) print("命令執行完畢!") NewTelnetClient.Logout() else: print(NewTelnetClient.StrErr) NewTelnetClient.Disconnect() time.sleep(2)
配置文件NetConfig.ini內容:code
[IP地址1]
EquipmentName=設備名稱
Username=用戶名稱
Password=用戶密碼
CommandSet=dis mac-address,dis arp,......,dis cuorm
[IP地址2]
EquipmentName=設備名稱
Username=用戶名稱
Password=用戶密碼
CommandSet=dis mac-address,dis arp,......,dis cu對象
......ip
[IP地址n]
EquipmentName=設備名稱
Username=用戶名稱
Password=用戶密碼
CommandSet=dis mac-address,dis arp,......,dis cuci