10

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?

stanleyxu2005
  • 8,081
  • 14
  • 59
  • 94

4 Answers4

12

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.

Pavel Repin
  • 30,663
  • 1
  • 34
  • 41
  • 1
    Thanks for this tip. Is there an easy way to configure private keys for many clients? I have to check log files of 20 machines every week. This is the motivation of writing a python script. – stanleyxu2005 Aug 22 '09 at 20:49
  • Well... you'll just have to append your public key to ~/.ssh/authorized_keys on each of the machines. Perhaps, if your working set of machines doesn't change a lot, this will be a one time exercise. BTW, this is a pretty neat article about setting up SSH Agent and more: http://unixwiz.net/techtips/ssh-agent-forwarding.html – Pavel Repin Aug 22 '09 at 21:18
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..
avasal
  • 14,350
  • 4
  • 31
  • 47
1

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.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

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

JJ Geewax
  • 10,342
  • 1
  • 37
  • 49
  • After having tried so many different solutions, I think this library is the best practice for now. I even do not have to configure non-password login to run any script on foreign nodes over LAN. – stanleyxu2005 Mar 07 '14 at 03:20