1. 程式人生 > >Python3+telnetlib實現telnet客戶端

Python3+telnetlib實現telnet客戶端

encode tcl 之前 編碼 tps 連接失敗 lan cli get

一、程序要點說明

python實現telnet客戶端的六個關鍵問題及其答案是:

使用什麽庫實現telnet客戶端----telnetlib

怎麽連接主機----兩種方法,一種是在實例化時傳入ip地址連接主機(tn = telnetlib.Telnet(host_ip,port=23)),第二種是,先不傳參數進行實例化再用open方法連接主機(我這裏使用的方法)

怎麽輸入用戶名密碼----我們使用read_untilb函數監聽,出現標誌後使用write方法向服務端傳輸用戶名密碼

怎麽執行命令----仍然是使用write方法向服務端傳送命令,不管向服務端傳送什麽數據都用write;不過要註意需要編碼成bytes類型

怎麽獲取命令執行結果----使用read_very_eager()方法,該方法獲取的內容是上次獲取之後本次獲取之前的所有輸入輸出;由於獲取到的是bytes類型要decode解碼一下

怎麽退出telnet---退出telnet使用write方法向服務器提交exit命令即可

二、程序源代碼

技術分享圖片
import logging
import telnetlib
import time


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網絡連接失敗%host_ip) return False # 等待login出現後輸入用戶名,最多等待10秒 self.tn.read_until(b
login: ,timeout=10) self.tn.write(username.encode(ascii) + b\n) # 等待Password出現後輸入用戶名,最多等待10秒 self.tn.read_until(bPassword: ,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 Login incorrect not in command_result: logging.warning(%s登錄成功%host_ip) return True else: logging.warning(%s登錄失敗,用戶名或密碼錯誤%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.warning(命令執行結果:\n%s % command_result) # 退出telnet def logout_host(self): self.tn.write(b"exit\n") if __name__ == __main__: host_ip = 192.168.220.129 username = root password = abcd1234 command = whoami telnet_client = TelnetClient() # 如果登錄結果返加True,則執行命令,然後退出 if telnet_client.login_host(host_ip,username,password): telnet_client.execute_some_command(command) telnet_client.logout_host()
View Code

參考:

https://docs.python.org/3/library/telnetlib.html

Python3+telnetlib實現telnet客戶端