stanleyxu2005
stanleyxu2005

Reputation: 8241

how to get console output from a remote computer (ssh + python)

I have googled "python ssh". There is a wonderful module pexpect, which can access a remote computer using ssh (with password).

After the remote computer is connected, I can execute other commands. However I cannot get the result in python again.

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

How to get the result of ps -ef in my case?

Upvotes: 12

Views: 26599

Answers (4)

avasal
avasal

Reputation: 14872

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..

Upvotes: 3

Pavel Repin
Pavel Repin

Reputation: 30963

Have you tried an even simpler approach?

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

Granted, this only works because I have ssh-agent running preloaded with a private key that the remote host knows about.

Upvotes: 14

JJ Geewax
JJ Geewax

Reputation: 10579

You might also want to investigate paramiko which is another SSH library for Python.

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328790

Try to send

p.sendline("ps -ef\n")

IIRC, the text you send is interpreted verbatim, so the other computer is probably waiting for you to complete the command.

Upvotes: 1

Related Questions