リモートコンピュータからコンソール出力を取得する方法(SSH +のpython)

StackOverflow https://stackoverflow.com/questions/1311697

質問

私は "のpythonのssh" Googleで検索しています。 (パスワード付き)にsshを使用してリモートコンピュータにアクセスすることができます素晴らしいモジュール pexpect のは、あります。

リモートコンピュータが接続された後、

、私は他のコマンドを実行することができます。しかし、私は再びpythonで結果を得ることができません。

p = pexpect.spawn("ssh user@remote_computer")
print "connecting..."
p.waitnoecho()
p.sendline(my_password)
print "connected"
p.sendline("ps -ef")
p.expect(pexpect.EOF) # this will take very long time
print p.before

私の場合にはps -efの結果を取得するには?

役に立ちましたか?

解決

また、Pythonのための別のSSHライブラリである paramiko に調査したいかもしれません。

他のヒント

あなたも、単純なアプローチを試みたことがありますか?

>>> from subprocess import Popen, PIPE
>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
...                        stdout=PIPE).communicate()
>>> print(stdout)
私は、リモートホストが知っていることを秘密鍵でプリロード実行しssh-agentているので、

確かに、これはのみ動作します。

child = pexpect.spawn("ssh user@remote_computer ps -ef")
print "connecting..."
i = child.expect(['user@remote_computer\'s password:'])
child.sendline(user_password)
i = child.expect([' .*']) #or use i = child.expect([pexpect.EOF])
if i == 0:
    print child.after # uncomment when using [' .*'] pattern
    #print child.before # uncomment when using EOF pattern
else:
    print "Unable to capture output"


Hope this help..

タグに送信するようにしてください
p.sendline("ps -ef\n")

IIRC、あなたが送ったテキストを逐語的に解釈されるため、コマンドを完成するために他のコンピュータは、おそらく待っています。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top