使用telnetlib实时读取输出

9
我将使用Python的telnetlib来telnet到某台机器并执行一些命令,我想要获取这些命令的输出。
目前的情况是这样的:
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("command1")
tn.write("command2")
tn.write("command3")
tn.write("command4")
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op
#here I get the whole output

现在,我可以在sess_op中获取所有的合并输出。

但是,我想要在command1执行后立即获取其输出,在command2执行之前,就像在另一台机器的shell中一样,如下所示 -

tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("command1")
#here I want to get the output for command1
tn.write("command2")
#here I want to get the output for command2
tn.write("command3")
tn.write("command4")
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op
3个回答

10

我在使用telnetlib时遇到了类似的问题。

后来我发现每个命令末尾都缺少回车和换行符,并为所有命令执行了read_eager。就像这样:

 tn = telnetlib.Telnet(HOST, PORT)
 tn.read_until("login: ")
 tn.write(user + "\r\n")
 tn.read_until("password: ")
 tn.write(password + "\r\n")

 tn.write("command1\r\n")
 ret1 = tn.read_eager()
 print ret1 #or use however you want
 tn.write("command2\r\n")
 print tn.read_eager()
 ... and so on

不仅仅只写出命令,例如:

 tn.write("command1")
 print tn.read_eager()
如果只使用 "\n" 对你来说可以正常工作,那么只添加一个 "\n" 或许就足够了,而我这里则必须使用 "\r\n",但我还没有尝试只使用一个换行符的情况。

它在我的情况下不起作用,只显示“_”,我只是输入了“show version”命令。 - ImranRazaKhan

4

您必须参考telnetlib模块的文档,可以在这里找到。
尝试如下 -

tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("command1")
print tn.read_eager()
tn.write("command2")
print tn.read_eager()
tn.write("command3")
print tn.read_eager()
tn.write("command4")
print tn.read_eager()
tn.write("exit\n")

sess_op = tn.read_all()
print sess_op

0

我也遇到了同样的问题,read_very_eager()函数没有显示任何数据。从一些帖子中得到的想法是,该命令需要一些时间来执行。因此使用了time.sleep()函数。

代码片段:

tn.write(b"sh ip rou\r\n")
time.sleep(10)
data9 = tn.read_very_eager()
print(data9)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接