使用telnetlib实时读取输出

the*_*est 6 python telnetlib

我正在使用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
Run Code Online (Sandbox Code Playgroud)

现在,我可以在sess_op中获得所有合并输出.

但是,我想要的是在执行command1之后立即获取command1的输出,就像我在其他机器的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
Run Code Online (Sandbox Code Playgroud)

Pyt*_*nia 8

我在使用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
Run Code Online (Sandbox Code Playgroud)

而不是像以下那样编写命令:

 tn.write("command1")
 print tn.read_eager()
Run Code Online (Sandbox Code Playgroud)

如果它对你只有一个"\n",只添加一个"\n"就可以了,而不是"\ r \n",但在我的情况下,我不得不使用"\ r \n"而且我还没有尝试了一个新的生产线.


Pus*_*ade 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
Run Code Online (Sandbox Code Playgroud)