3 """This runs 'ls -l' on a remote host using SSH. At the prompts enter hostname,
6 $Id: sshls.py 489 2007-11-28 23:40:34Z noah $
14 def ssh_command(user, host, password, command):
15 """This runs a command on the remote host. This could also be done with the
16 pxssh class, but this demonstrates what that class does at a simpler level.
17 This returns a pexpect.spawn object. This handles the case when you try to
18 connect to a new host and ssh asks you if you want to accept the public key
19 fingerprint and continue connecting. """
21 ssh_newkey = 'Are you sure you want to continue connecting'
22 child = pexpect.spawn('ssh -l %s %s %s' % (user, host, command))
23 i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
26 print 'SSH could not login. Here is what SSH said:'
27 print child.before, child.after
29 if i == 1: # SSH does not have the public key. Just accept it.
31 child.expect('password: ')
32 i = child.expect([pexpect.TIMEOUT, 'password: '])
35 print 'SSH could not login. Here is what SSH said:'
36 print child.before, child.after
38 child.sendline(password)
44 host = raw_input('Hostname: ')
45 user = raw_input('User: ')
46 password = getpass.getpass('Password: ')
47 child = ssh_command(user, host, password, '/bin/ls -l')
48 child.expect(pexpect.EOF)
51 if __name__ == '__main__':
54 except Exception as e: