Python 3.3 telnet 问题

1 投票
2 回答
5499 浏览
提问于 2025-04-17 13:42

我一直在为这个问题抓狂。我想用Python收集一个telnet的日志。在普通的telnet中,我只需要打开telnet,然后使用:

set logfile test.xml

问题是,用Python我不知道怎么先执行这个命令。当我运行这个

try:
    tn = telnetlib.Telnet()
    tn.write(b"set logfile test.xml" + b"\r")
    tn.open(IP, 223, 8192)
except socket.timeout:
    print ("socket timeout")
    sulk()

时,我收到了这个错误:

Traceback (most recent call last):
  File "C:xxxxxxxx.py", line 18, in <module>
    tn.write(b"set logfile test.xml" + b"\r")
  File "C:\Python33\lib\telnetlib.py", line 282, in write
    self.sock.sendall(buffer)
AttributeError: 'NoneType' object has no attribute 'sendall'

如果我不设置日志文件,脚本运行得很好,直接打开IP和端口就可以了。为了解决这个问题,我用Python写入一个文件。但不知道为什么,这样做需要很长时间,超过5分钟。如果我直接通过telnet运行这些命令,通常不到10秒就能完成……

telnet
set logfile test.xml
o xxx.xxx.xxx.xxx xxx
>>commandx
>>commandy

All the data I need is here and in the log file 

所以,有没有什么办法可以在打开IP和端口之前设置日志文件呢?提前谢谢大家!

2 个回答

2

没什么。

set logfile 这个命令并不是 telnet 协议的一部分,它是你喜欢的 telnet 客户端的一个命令。现在你正在使用另一个 telnet 客户端的版本,这个版本没有这个命令(也没有必要尝试把它发送到 远程 系统)。

据我所知,python 的 telnetlib 中没有内置的日志记录功能可以推荐作为替代。

3

你这个做法有点反了。我猜你是想把信息记录到一个文件里,然后再把这个文件读进你的Python脚本里去处理。其实你应该先把telnet会话的输出存到一个变量里。这样你就可以进一步处理这些数据,甚至如果需要的话,还可以把它写入文件。

import telnetlib

host    = "host.example.com"
port    = 223
timeout = 9999

try:
    session = telnetlib.Telnet(host, port, timeout)
except socket.timeout:
    print ("socket timeout")
else:
    session.write("command1\n")
    session.write("command2\n")
    output = session.read_all()
    # output now contains the text you want
    # so now you can do something with it:
    with open("test.xml", "w") as logfile:
        logfile.write(output)

如果输出的数据量比较大,你可以分块读取:

import time, telnetlib

host    = "host.example.com"
port    = 223
timeout = 9999

try:
    session = telnetlib.Telnet(host, port, timeout)
except socket.timeout:
    print ("socket timeout")
else:
    session.write("command1\n")
    session.write("command2\n")
    with open("test.xml", "w") as logfile:
        output = session.read_some()
        while output:
            logfile.write(output)
            time.sleep(0.1)  # let the buffer fill up a bit
            output = session.read_some()

撰写回答