python實現Telnet功能
阿新 • • 發佈:2018-12-15
# -*- coding: utf-8 -*- import logging import telnetlib import time import sys import os host_ip = '10.63.194.1' username = 'ROOT' password = '[email protected]' telnet_client = [] curPath = os.path.dirname(os.path.abspath(sys.argv[0])) def getFileTime(): curTime = time.strftime('%Y%m%d_%H%M%S',time.localtime(time.time())) return curTime #列印中文要txt開啟,或改格式,把列印改為英文 logPath = curPath + '\\..\\log\\' + getFileTime() +'.log' print(logPath) logging.basicConfig(level = logging.DEBUG, format='[%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S,%a', filename = logPath, filemode='w') class TelnetClient(): def __init__(self,): self.tn = telnetlib.Telnet() # 此函式實現telnet登入主機 def login_host(self,host_ip,username,password): try: # self.tn = telnetlib.Telnet(host_ip,port=23) self.tn.open(host_ip,port=23) except: logging.warning('%s failed to connect !'%host_ip) return False # 等待login出現後輸入使用者名稱,最多等待10秒 self.tn.read_until(b'Username:',timeout=10) self.tn.write(username.encode('ascii') + b'\n') # 等待Password出現後輸入使用者名稱,最多等待10秒 self.tn.read_until(b'Password:',timeout=10) self.tn.write(password.encode('ascii') + b'\n') # 延時兩秒再收取返回結果,給服務端足夠響應時間 time.sleep(2) # 獲取登入結果 # read_very_eager()獲取到的是的是上次獲取之後本次獲取之前的所有輸出 command_result = self.tn.read_very_eager().decode('ascii') if 'error' not in command_result: logging.warning('%s connected ssuccess !'%host_ip) return True else: logging.warning('%s failed to login,username or password error !'%host_ip) return False # 此函式實現執行傳過來的命令,並輸出其執行結果 def execute_some_command(self,command): # 執行命令 self.tn.write(command.encode('ascii')+b'\n') time.sleep(2) # 獲取命令結果 command_result = self.tn.read_very_eager().decode('ascii') logging.debug('%s' % command_result) # 退出telnet def logout_host(self): self.tn.write(b"exit\n") def writeC(command): telnet_client.execute_some_command(command) def inputCommand(): cont = 'con t' aclNum = ' 300' writeC(cont) writeC(aclNum) for index in range(255): index =index + 1 writeC('no rule ' + str(index)) if __name__ == '__main__': telnet_client = TelnetClient() # 如果登入結果返加True,則執行命令,然後退出 if telnet_client.login_host(host_ip,username,password): inputCommand() telnet_client.logout_host()