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

stanleyxu2005 picture stanleyxu2005 · Aug 21, 2009 · Viewed 17.2k times · Source

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?

Answer

Pavel Repin picture Pavel Repin · Aug 22, 2009

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.