telnetlib read_until() 不匹配任何内容
telnetlib read_until() Does Not Match Anything
我正在编写一个 Python 脚本来解析来自端口 10001 上的远程 telnet 服务器的一些数据。基本上,当我键入:
$ telnet <host> 10001
终端打印出来:
Trying <host>...
Connected to static-<host>.nycmny.fios.verizon.net.
Escape character is '^]'.
# empty line for prompt
在评论的空行上,我应该输入如下命令('\n'
代表点击 return):
^Ai20101\n
# server prints out data
somedatalinehere
^]
# escape to telnet prompt like below
telnet>
telnet> quit\n
connection closed.
# returns to local terminal prompt
但是,当我在 Python 中执行此操作时:
tn = telnetlib.Telnet(host, 10001)
tn.read_until("\r\n", timeout=1) # nothing matched, returns ''
tn.read_until("", timeout=1) # nothing matched, returns ''
# thus
tn.write("^Ai20101\n")
time.sleep(0.1) # wait 0.1s for next prompt
tn.write("^]")
time.sleep(0.1)
tn.write("quit\n")
tn.read_all() # This hangs as if connection wasn't closed.
实际命令提示符($
标志或类似的东西)之前的所有输出都是由您自己的 telnet 客户端生成的,而不是由服务器生成的。
所以请尝试以下操作:
tn.read_until("$")
如果成功,这意味着您连接正常并可以发出命令。
read_all()
应该'hang'。引自 docs:
Telnet.
read_all()
Read all data until EOF; block until connection closed.
编辑:
实际上,您发布了没有 服务器的响应。正如我之前所说,所有这些东西都是由客户端生成的。
# the prompt starts here
是什么意思?我认为这意味着在所有输出之后你会看到一个命令提示符,看起来像这样:
ForceBru @ iMac-ForceBru:~ $
因此,您应该阅读到这一行以确保连接成功。
我通过使用 pexpect 的子进程让它工作,它比 telnetlib 灵活得多。
import pexpect
import time
child = pexpect.spawn('telnet <host> 10001')
child.sendcontrol('a')
child.send('i20101' + '\n')
无需 read_until()
,这就奏效了。
我正在编写一个 Python 脚本来解析来自端口 10001 上的远程 telnet 服务器的一些数据。基本上,当我键入:
$ telnet <host> 10001
终端打印出来:
Trying <host>...
Connected to static-<host>.nycmny.fios.verizon.net.
Escape character is '^]'.
# empty line for prompt
在评论的空行上,我应该输入如下命令('\n'
代表点击 return):
^Ai20101\n
# server prints out data
somedatalinehere
^]
# escape to telnet prompt like below
telnet>
telnet> quit\n
connection closed.
# returns to local terminal prompt
但是,当我在 Python 中执行此操作时:
tn = telnetlib.Telnet(host, 10001)
tn.read_until("\r\n", timeout=1) # nothing matched, returns ''
tn.read_until("", timeout=1) # nothing matched, returns ''
# thus
tn.write("^Ai20101\n")
time.sleep(0.1) # wait 0.1s for next prompt
tn.write("^]")
time.sleep(0.1)
tn.write("quit\n")
tn.read_all() # This hangs as if connection wasn't closed.
实际命令提示符($
标志或类似的东西)之前的所有输出都是由您自己的 telnet 客户端生成的,而不是由服务器生成的。
所以请尝试以下操作:
tn.read_until("$")
如果成功,这意味着您连接正常并可以发出命令。
read_all()
应该'hang'。引自 docs:
Telnet.
read_all()
Read all data until EOF; block until connection closed.
编辑:
实际上,您发布了没有 服务器的响应。正如我之前所说,所有这些东西都是由客户端生成的。
# the prompt starts here
是什么意思?我认为这意味着在所有输出之后你会看到一个命令提示符,看起来像这样:
ForceBru @ iMac-ForceBru:~ $
因此,您应该阅读到这一行以确保连接成功。
我通过使用 pexpect 的子进程让它工作,它比 telnetlib 灵活得多。
import pexpect
import time
child = pexpect.spawn('telnet <host> 10001')
child.sendcontrol('a')
child.send('i20101' + '\n')
无需 read_until()
,这就奏效了。