2017-10-31 3 views
0

私は、pexpectを使用してリモートマシンを制御する非常に簡単なプログラムを作成しようとしています。しかし、リモートシステムは送信されたコマンドに反応しません。ここでシステムがpexpectコマンドに応答していません

は、ソースコードである:ここで

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 

import pexpect 
import sys 
child = pexpect.spawn('telnet 192.168.2.81 24') 
res = child.expect('/ # ') 
print(res) 
res = child.sendline('touch foo') 
print(res) 

が出力されますので、

0 
10 

、限り私は理解して、コマンドが正常に実行されますが、ターゲット・システムには結果がありません、つまりfooのファイルは作成されません。

誰かが私を助けることができますか?

答えて

1

pexpect.spawn()後に次の行を追加するか、あなたは何も見えないだろう。

# for Python 2 
child.logfile_read = sys.stdout 

# for Python 3 
child.logfile_read = sys.stdout.buffer 
あなたはまた、(そうでない場合、スクリプトは直ちに終了後 sendline('touch foo')ので touch fooを実行する機会がないでしょう)最後に次のステートメントが必要

:マニュアルによると

child.sendline('exit') 
child.expect(pexpect.EOF) 

を:

The logfile_read and logfile_send members can be used to separately log the input from the child and output sent to the child. Sometimes you don’t want to see everything you write to the child. You only want to log what the child sends back. For example:

child = pexpect.spawn('some_command') 
child.logfile_read = sys.stdout 
+0

ありがとうございました! 'child.sendline( 'exit')'と 'child.expect(pexpect.EOF)'が働いていました。 'child.logfile_read = sys.stdout'はどうでしょうか?' TypeError:write()引数はバイトではなくstrでなければなりませんが、それが働いても何の利益も見られません。それを無視し、ファイルの終わりに関連する推奨事項のみを使用することができます。 –

+1

が見つかりました:https://stackoverflow.com/questions/35330424/expect-in-python3-is-throwing-error-as-must-be-in-str-not-bytes。私の答えを更新しました。 – pynexj

関連する問題