2012-04-12 10 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にすべて統合出力を得ることができます。

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
- ここに示したように、私が欲しいもの

しかしには、すぐに私は他のマシンのシェルで働いているかのようにその実行後コマンド2の実行前のCommand1の出力を得ることです

telnetlibモジュールhereのドキュメントを参照する必要があります。
はこれを試してみてください - 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 
+4

私の場合は動作しません! – theharshest

7

次に、各コマンドの最後に改行がありません。新しい行があり、すべてのコマンドで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"を使用しなければならなかったと私はまだ新しい行で試していない。

関連する問題