1 telnetlib
1.1 簡單介紹
是python的內置模塊,支持telnet遠程操作,只需要導入就可以使用了,導入方法:
import telnetlib
1.2 快速入門
Step1:編輯文件suite\case\show_how\raw_telnet.py,內容如下:
import time import telnetlib try: #create a telnet instance with given hostname and port. tn= telnetlib.Telnet("192.168.1.1", '23') #read util appeared the string 'login', timeout is 5 seconds. tn.expect([b'login '], 5) #write a string to the telnet socket, using 'utf-8' to encode is suggested. tn.write("admin\n".encode('UTF-8')) tn.expect([b'Password'], 5) tn.write("90123456\n".encode('UTF-8')) tn.write("tcapi get SysInfo_Entry FirmVer\n".encode("utf-8")) #sleep 1 seconds is suggested. time.sleep(1) #Read everything that's possible without blocking in I/O result = tn.read_very_eager() #output string to console. print(result) tn.close except Exception as e: #something wrong. print(e) finally: #run end pass
Step2:執行Run的快捷鍵,Alt+Shift+F10
Step3:執行后會在console端輸出如下信息
1 C:\Users\20002106\AppData\Local\Programs\Python\Python36\python.exe "D:/auto test/Together_v0.2/suite/case/show_how/raw_telnet.py" 2 ["b'tcapi get SysInfo_Entry FirmVer\\r", 'DSL-3782 FTTxv1.00t\\r', "# '"] 3 4 Process finished with exit code 0
1.3 代碼解釋
在我們平時使用telnet的時候,幾乎都是執行連接、輸入命令、查看運行結果和斷開等操作,與這幾個操作相對應的,可以分別調用telnetlib的如下相關函數:
1.3.1 連接
Telnet是一個類,調用下面函數對該類進行初始化,並返回一個實例,在后續操作中可以調用該實例下的方法。初始化的參數包括telnet服務器端的IP地址、端口號和登錄時的超時時間。
tn= telnetlib.Telnet(host= None, port=0,timeout= socket._GLOBAL_DEFAULT_TIMEOUT)
1.3.2 斷開
當不再需要連接telnet時,可以執行斷開操作關閉此套接字。函數如下:
tn.close()
1.3.3 寫入數據
向socket中寫入字符串,如下操作可以用來輸入命令
tn.write(buffer)
建議使用上面這個函數時,buffer字符串最好用UTF-8轉碼,比如:
tn.write("tcapi get SysInfo_Entry FirmVer\n".encode("utf-8"))
1.3.4 調式信息
如果想要打印telnet過程中的詳細信息到console,可以通過如下函數設置tn.debuglevel值,值越高信息越詳細。設置方法如下:
tn.set_debuglevel(1)
1.3.5 讀取數據
Telnetlib庫中存放數據是用的緩沖區機制,因此輸入命令后數據並不會一下子就返回,而是先放到了緩沖區中,而緩沖區中的信息何時到達就說不清楚了,也許很快,也許很慢,也許分別到達,也許一下子就到達了。 Telnetlib中許多讀數據和取數據的操作都是圍繞着這個緩沖區來的,常見的如下,這些函數的詳細說明見 [附錄A.1]:
Telnet.expect(list, timeout=None)
Telnet.read_until(expected, timeout=None)
上面幾個函數是當緩沖區中存在想要的數據時就返回,否則阻塞,timeout為超時時間;Telnet.expect(list, timeout=None)中的參數list支持正則表達式(such as .*)
Telnet.read_sb_data()
Telnet.read_very_lazy()
Telnet.read_lazy()
Telnet.read_eager()
Telnet.read_very_eager()
上面幾個函數是只要緩沖區中有數據就返回該數據,如果沒有就返回 b'', 該系列函數不會引起阻塞。這幾個函數間的區別還沒有仔細研究。
Telnet.read_some()
上面函數是只要緩沖區中有數據就返回該數據,如果沒有就阻塞直到緩沖區中有至少一字節為止。
Telnet.read_all()
上面函數是在緩沖區內容遇到EOF之前,會一直阻塞。在遇到EOF之后,返回之前所有的數據。不建議使用該函數,因為如果telnet的回顯中沒有EOF的話,這個函數會一直阻塞,直到telnet斷開為止。
1.4 reference
[1]. https://docs.python.org/3/library/telnetlib.html
A.1 Telnet.read_XXX

1 Telnet.expect(list, timeout=None): 2 """Read until one from a list of a regular expressions matches. 3 4 The first argument is a list of regular expressions, either 5 compiled (re.RegexObject instances) or uncompiled (strings). 6 The optional second argument is a timeout, in seconds; default 7 is no timeout. 8 9 Return a tuple of three items: the index in the list of the 10 first regular expression that matches; the match object 11 returned; and the text read up till and including the match. 12 13 If EOF is read and no text was read, raise EOFError. 14 Otherwise, when nothing matches, return (-1, None, text) where 15 text is the text received so far (may be the empty string if a 16 timeout happened). 17 18 If a regular expression ends with a greedy match (e.g. '.*') 19 or if more than one expression can match the same input, the 20 results are undeterministic, and may depend on the I/O timing. 21 22 """ 23 24 Telnet.read_sb_data(): 25 """Return any data available in the SB ... SE queue. 26 27 Return b'' if no SB ... SE available. Should only be called 28 after seeing a SB or SE command. When a new SB command is 29 found, old unread SB data will be discarded. Don't block. 30 31 """ 32 33 Telnet.read_very_lazy(): 34 """Return any data available in the cooked queue (very lazy). 35 36 Raise EOFError if connection closed and no data available. 37 Return b'' if no cooked data available otherwise. Don't block. 38 39 """ 40 41 Telnet.read_lazy(): 42 """Process and return data that's already in the queues (lazy). 43 44 Raise EOFError if connection closed and no data available. 45 Return b'' if no cooked data available otherwise. Don't block 46 unless in the midst of an IAC sequence. 47 48 """ 49 50 Telnet.read_eager(): 51 """Read readily available data. 52 53 Raise EOFError if connection closed and no cooked data 54 available. Return b'' if no cooked data available otherwise. 55 Don't block unless in the midst of an IAC sequence. 56 57 """ 58 59 Telnet.read_very_eager(): 60 """Read everything that's possible without blocking in I/O (eager). 61 62 Raise EOFError if connection closed and no cooked data 63 available. Return b'' if no cooked data available otherwise. 64 Don't block unless in the midst of an IAC sequence. 65 66 """ 67 68 Telnet.read_some(): 69 """Read at least one byte of cooked data unless EOF is hit. 70 71 Return b'' if EOF is hit. Block if no data is immediately 72 available. 73 74 """ 75 76 Telnet.read_all(): 77 """Read all data until EOF; block until connection closed.""" 78 79 Telnet.read_until(match, timeout=None): 80 """Read until a given string is encountered or until timeout. 81 82 When no match is found, return whatever is available instead, 83 possibly the empty string. Raise EOFError if the connection 84 is closed and no cooked data is available.