使用realtim中的telnetlib读取输出

2024-06-13 23:12:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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执行之前立即获得它的输出,就好像我在另一台机器的外壳中工作一样,如下所示-

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

Tags: the机器readoutputgetherepasswordtn
3条回答

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

然后我意识到一个丢失的回车和一个新的行在每个命令的末尾,并做了一个对所有命令的读取。像这样的:

 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”,但在我的情况下,我必须使用“\r\n”,而且我还没有尝试使用新的行。

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

代码段:

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

您必须参考telnetlib模块here的文档。
试试这个-

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

相关问题 更多 >