telnetlib-telnet客户端操作

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.
Telnet.read_XXX

 

posted on 2020-04-20 17:53  LiveWithACat  阅读(3139)  评论(0编辑  收藏  举报