Telnet输出解析

1 投票
1 回答
3808 浏览
提问于 2025-04-18 18:34

我现在正在尝试在Python 3.4中使用telnetlib库。
我想做的就是给我的接入点发送命令,然后获取一些响应。
我的代码是:

`import telnetlib
 import time

 user='admin'
 password='admin'
 host='192.168.1.1'


 try:
    tn=telnetlib.Telnet("host")
    tn.read_until(b"Login: ")
    tn.write(user.encode() + "\r\n".encode())
    tn.read_until(b"Password: ")
    tn.write(password.encode() + "\r\n".encode())
    print("Connection establised")
 except Exception:
    print("Connection failed")

 cmd="interface AccessPoint\r\n"
 tn.write(cmd.encode())
 cmd2="ssid TEST\r\n"
 tn.write(cmd2.encode())

 output=n.read_eager()
 while output:
    print(output.decode())
    time.sleep(.2)
    output=tn.read_eager()

例如,这段脚本应该把SSID的名字改成TEST。
然后我在Putty中这样做,效果很好:

enter image description here

但是当我尝试从我的脚本中读取响应时,我看到的东西像这样:

enter image description here

请问,这些符号是什么意思?
有没有办法把它们从我的日志中去掉?

附言:我尝试了其他所有读取方式,比如read_all。也试过不使用decode(),还有用decode('utf-8'),但这些符号总是出现。我还应该怎么做呢?

谢谢,Mairy。

1 个回答

1

你的接入点认为它在和一个终端模拟器对话。这些符号被称为“ANSI转义码”,这个名字来源于一个已经不再使用的标准ANSI X3.64。

字符串Escape-[-K的意思是“清除到行尾”。而字符串Escape-[-1-6-D的意思是“将光标向左移动16个空格”。

  • 你可以让你的接入点相信它不是在和一个终端模拟器对话,或者它是在和一个非ANSI的终端模拟器对话,或者

  • 你可以通过使用合适的正则表达式来从记录的字符串中删除这些符号,比如msg = re.sub('\x1b\\[\\d*[A-Z]', '', msg)

参考资料:

撰写回答