2012-04-12 41 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」,我還沒有嘗試過只是一個新的行。