10

「pythonssh」をグーグルで検索しました。pexpectssh(パスワード付き)を使用してリモートコンピュータにアクセスできる素晴らしいモジュールがあります。

リモートコンピュータが接続された後、他のコマンドを実行できます。ただし、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ですか?

4

4 に答える 4

11

もっと簡単な方法を試しましたか?

>>> from subprocess import Popen, PIPE
>>> stdout, stderr = Popen(['ssh', 'user@remote_computer', 'ps -ef'],
...                        stdout=PIPE).communicate()
>>> print(stdout)

確かに、これはssh-agent、リモート ホストが認識している秘密鍵をプリロードして実行しているためにのみ機能します。

于 2009-08-21T23:07:00.063 に答える
3
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..
于 2011-08-25T06:32:20.990 に答える
1

また、Python 用の別の SSH ライブラリであるparamikoを調べることもできます。

于 2009-08-21T19:08:36.253 に答える