telnetlib模塊的常用接口
telnetlib.Telnet(host, port, timeout) # 登錄 write() # 輸入命令 read_until(match) # 讀出響應,直到讀取到指定字符串 close() # 登出
一個簡單的例子
import telnetlib Host = "a.b.c.d" # 連接Telnet服務器 tn = telnetlib.Telnet(Host, port=23, timeout=10) tn.set_debuglevel(0) # 輸入登錄用戶名 tn.read_until(b'login: ') tn.write(b"zte" + b'\n') # 輸入登錄密碼 tn.read_until(b'Password: ') tn.write(b"Telnet@1234" + b'\n') tn.read_until(b'#') tn.write(b"cd /home/sd" + b'\n') tn.read_until(b'#') tn.write(b"ls -al" + b'\n') r = tn.read_until(b'#').decode('ASCII') r1 = r.split(r"\r\n") for i in r1: print(i) tn.close()
