2

Aloha,我正在创建一个teamspeakbot,并且想要写入和读取使用 TeamSpeak3 服务器创建的 telnet 会话

import telnetlib
tn = telnetlib.Telnet('localhost', 10011, 10)
tn.read_all()

我所期待的:

Connected to localhost
Escape character is '^]'.
TS3
Welcome to the TeamSpeak 3 ServerQuery interface, type "help" for a li...

但相反,我在 10 秒后超时:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/telnetlib.py", line 325, in read_all
    self.fill_rawq()
  File "/usr/lib/python2.7/telnetlib.py", line 516, in fill_rawq
    buf = self.sock.recv(50)
socket.timeout: timed out

我如何阅读telnet 连接告诉我的所有内容,然后再向其写入一些内容(例如登录过程和提交命令并获得响应......)

解决方案是

tn.read_very_eager()

我的代码现在看起来像这样:

import telnetlib, time
tn = telnetlib.Telnet('localhost', 10011, 10)
tn.write('help\n')
time.sleep(0.05)
print(tn.read_very_eager())
4

1 回答 1

0

read_all() 阻塞,直到到达 EOF*,或者直到您的超时。虽然我没有太多使用 telnetlib,但我认为它是用于显示某些内容然后关闭连接的服务。

您如何处理以下代码:

tn = telnetlib.Telnet('localhost', 10011, 10)
tn.read_some()

* https://docs.python.org/2/library/telnetlib.html#telnetlib.Telnet.read_all

于 2014-11-09T22:09:49.523 回答