I found a strange problem with python's telnetlib module. When I use the telnetlib to access a server and try to get the information, it always show some strange character, and I am sure its not the encoding problem, the output just like below:
1[2J[3;1HPort Type IP1 IP2 IP3 IP4[4;1H 01 Real COM [5;1H 02 Real COM [6;1H 03 Real COM [7;1H 04 Real COM [8;1H 05 Real COM [9;1H 06 Real COM [10;1H 07 Real COM [11;1H 08 Real COM [12;1H 09 Real COM [13;1H 10 Real COM [14;1H 11 Real COM [15;1H 12 Real COM [16;1H 13 Real COM [17;1H 14 Real COM [18;1H 15 Real COM [19;1H 16 Real COM [20;1H
But when I use some shell-like applications to telnet to the server, what I get is quite good and neat, there are no strange characters. Below is the result that I got using cygwin:
Port Type IP1 IP2 IP3 IP4
01 Real COM Listen
02 Real COM Listen
03 Real COM 147.128.14.147
04 Real COM Listen
05 Real COM Listen
06 Real COM Listen
07 Real COM Listen
08 Real COM Listen
09 Real COM Listen
10 Real COM Listen
11 Real COM Listen
12 Real COM Listen
13 Real COM Listen
14 Real COM Listen
15 Real COM Listen
16 Real COM Listen
Has anyone met the same problem? And why does this happen? How can I get a "neat" result when I use telnetlib?
Below is the simple script:
import telnetlib
if __name__ == '__main__':
HOST = '10.185.20.2'
tn = telnetlib.Telnet(HOST)
r1 = tn.read_until('selection: ', 5)
print r1
tn.write('8' + '\r\n')
r2 = tn.read_until('selection: ', 5)
print r2
tn.write('1 ' + '\r\n')
r3 = tn.read_until('cancel ...', 5)
print r3
Those look a lot like terminal escape sequences, with the escape byte (0x1b
) missing. In many terminals, certain sequences of bytes have special effects, such as changing the color, moving the cursor, etc. For example, \x1b[3;1H
means "move the cursor to row 3, column 1" on VT100 or compatible terminals, which most terminals are. (The VT100 is long dead, but many terminal applications such as Terminal.app
, GNOME Terminal, and xterm
, still use those escape sequences.)
You might be getting the escape byte (0x1b
), but it's being filtered somehow. repr
helps here, as it shows you what is actually in your string. You can get a list of common escape sequences, too.