1

我想用来select.select()阻止循环,直到准备好从 telnet 会话列表中读取一些数据。但是,下面的代码不起作用,并且调用select.select()立即返回,没有要读取的数据。我在 Ubuntu 10.4 下使用 python 2.7.3。

tn = telnetlib.Telnet(IP,23,TIMEOUT)
# [... logging and password omitted ..]

while True:
    logging.info("%d - waiting on select for data" % self.id)
    read_ready, write_ready, expt_ready = select.select([ tn.get_socket() ],[],[])
    logging.info("%d - select returned" % self.id)
    if len(read_ready) == 1:
        data = tn.read_eager()
        logging.info("%d read %d characters" % (self.id, len(data)))
        # ... continue processing the data...

输出示例:

2013-08-23 10:37:28,634 - INFO: 1 - waiting on select for data
2013-08-23 10:37:28,672 - INFO: 1 - select returned
2013-08-23 10:37:28,673 - INFO: 1 read 0 characters
2013-08-23 10:37:28,833 - INFO: 1 - waiting on select for data
2013-08-23 10:37:28,874 - INFO: 1 - select returned
2013-08-23 10:37:28,874 - INFO: 1 read 0 characters
2013-08-23 10:37:29,029 - INFO: 1 - waiting on select for data
2013-08-23 10:37:29,073 - INFO: 1 - select returned
2013-08-23 10:37:29,074 - INFO: 1 read 0 characters

一个例子set_debuglevel(1)

2013-08-23 11:50:29,019 - INFO: 1 - waiting on select for data
2013-08-23 11:50:29,062 - INFO: 1 - select returned
Telnet(10.2.3.15,23): recv '\xff\xfe\x01'
Telnet(10.2.3.15,23): IAC DONT 1
2013-08-23 11:50:29,062 - INFO: 1 read 0 characters
2013-08-23 11:50:29,063 - INFO: 1 - waiting on select for data
2013-08-23 11:50:29,069 - INFO: 1 - select returned
Telnet(10.2.3.15,23): recv '\xff\xfe!'
Telnet(10.2.3.15,23): IAC DONT 33
2013-08-23 11:50:29,069 - INFO: 1 read 0 characters
2013-08-23 11:50:29,070 - INFO: 1 - waiting on select for data
2013-08-23 11:50:29,110 - INFO: 1 - select returned
Telnet(10.2.3.15,23): recv '\xff\xfc\x03'
Telnet(10.2.3.15,23): IAC WONT 3
2013-08-23 11:50:29,110 - INFO: 1 read 0 characters
4

2 回答 2

1

正如“Stefano M”所建议的那样,这个问题与 telnet 会话选项协商有关。出于某种原因,客户端和服务器不断地交换选项,所以select.select()永远不会被阻塞(总是有数据要读取)。

我通过设置选项协商回调找到了解决方法。

Telnet.set_option_negotiation_callback(callback)
每次在输入流上读取 telnet 选项时,都会使用以下参数调用此回调(如果已设置):回调(telnet 套接字,命令(DO/DONT/WILL/WONT),选项)。telnetlib 之后不执行任何其他操作。

于 2013-08-23T12:22:00.840 回答
0

答案在文档中:(pydoc telnetlib):

可以将 Telnet 对象传递给以select.select()等待更多数据可用。请注意,在这种情况下, 即使套接字上有数据,read_eager()也可能返回,因为协议协商可能已经吃掉了数据。''

从调试输出中可以清楚地看出,远程端正在发送 telnet 命令而不是实际数据,因此您必须调试 telnet 握手。

于 2013-08-23T09:08:44.257 回答