2012-04-12 40 views
4

我正在使用Python的telnetlib telnet到某台机器并执行少量命令,我想获取这些命令的输出。实时读取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") 
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。

但是,我想要的是执行后立即命令2的执行之前,如果我在其他机器的外壳正在努力让Command 1的输出,如下所示 -

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 

回答

2

您必须参考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 
+4

它不工作在我的情况! – theharshest 2012-04-25 10:35:58

7

我遇到了类似的东西与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”但在我的情况下,我不得不使用“\ r \ n”,我还没有尝试过只是一个新的行。