2017-01-08 1 views
2

以下のコードを確認してください(わかりやすく)。Paramikoを使用してリモートマシン上で実行されるコマンドからstderrを返す方法は?

コード:

import sys 
import paramiko 

def execute_command_on_remote_machine(ip_addr, command): 
    try: 
     client = paramiko.SSHClient() 
     client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 

     client.connect(str(ip_addr), username='root', password='****') 
     chan = client.get_transport().open_session() 
     #chan.get_pty() 

     stdin, stderr, stdout = [], [], [] 
     stdin, stdout, stderr = client.exec_command(command, get_pty=True) 

     err_list = [line for line in stderr.read().splitlines()] 
     out_list = [line for line in stdout.read().splitlines()] 

     client.close() 
     return out_list, err_list 
    except Exception, e: 
     print str(e) 
     sys.exit(1) 


output, error = execute_command_on_remote_machine("*.*.*.*", "dinesh") 

print "Output is - ",output 
print "Error is - ",error 

出力:

D:\dsp_jetbrains\AWS_Persistence>python chk.py 
Output is - ['bash: dinesh: command not found'] 
Error is - [] 

問題:入力として

ます私は間違ったコマンドを合格していると私は "dinesh:command not foundは" 期待印刷されたウィットh "エラーは"です。しかし、それは "出力"で来ています。

質問:

どのようexec_commandparamikoでの作業のために出力し、エラーをでしょうか?

追加のテストケース:

は、私も存在するが、そのコマンドに間違った入力を渡されたコマンドを試してみました。例 - lsof -f dinesh

結果は同じです。

D:\dsp_jetbrains\AWS_Persistence>python chk.py 
Output is - ['lsof: unknown file struct option: d', 'lsof: unknown file struct 
option: i', 'lsof: unknown file struct option: n', 'lsof: unknown file struct op 
tion: e', 'lsof: unknown file struct option: s', 'lsof: unknown file struct opti 
on: h', 'lsof 4.87', ' latest revision: ftp://lsof.itap.purdue.edu/pub/tools/uni 
x/lsof/', ' latest FAQ: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/FAQ', ' l 
atest man page: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/lsof_man', ' usag 
e: [-?abhKlnNoOPRtUvVX] [+|-c c] [+|-d s] [+D D] [+|-f[gG]] [+|-e s]', ' [-F [f] 
] [-g [s]] [-i [i]] [+|-L [l]] [+m [m]] [+|-M] [-o [o]] [-p s]', '[+|-r [t]] [-s 
[p:s]] [-S [t]] [-T [t]] [-u s] [+|-w] [-x [fl]] [-Z [Z]] [--] [names]', "Use t 
he ``-h'' option to get more help information."] 
Error is - [] 

答えて

1

あなたが必要と思わない限り、get_ptyを使用しないでください。

chan.get_pty() 

および変更:除去検討

stdin, stdout, stderr = client.exec_command(command, get_pty=True) 

に:

stdin, stdout, stderr = client.exec_command(command) 
DOCS

より:

要求疑似ターミナルサーバから。これは、通常、クライアントチャネルを作成した直後に使用され、invoke_shellで起動されたシェルに対して基本的な端末セマンティクスを提供するようサーバに要求します。 exec_commandで単一のコマンドを実行する場合は、このメソッドを呼び出す必要はありません(または望ましい)。

pseudo-terminalは、ユーザーが接続されているようにssh接続を表示する場合に使用します。これは珍しいことです。 1つの工夫された例は、ansi-terminalシーケンスを送受信することによって遠端でVIMを実行したい場合です。

get_ptyを指定しないと、リモートで実行されるコマンドは、単純にstdin/stdout/stderrトリオをパイピングのように接続します。

get_ptyの必要性の希少性は、デフォルトではない可能性があります。

+0

私はその行にコメントし、それをチェックしました。しかし問題はまだそこにある。まだエラー文字列が出力されています。 –

+0

2番目のget_ptyリクエストが見つかりませんでした。編集済みの回答 –

+0

を参照してください。それがうまくいって、私はそれを答えとして受け入れます。なぜこれが起こるのか説明していただけますか?私はドキュメンテーションのリンクをチェックしましたが、私の問題の文脈を理解できませんでした。 –

関連する問題