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 $
12 def ssh_command (user, host, password, command):
14 """This runs a command on the remote host. This could also be done with the
15 pxssh class, but this demonstrates what that class does at a simpler level.
16 This returns a pexpect.spawn object. This handles the case when you try to
17 connect to a new host and ssh asks you if you want to accept the public key
18 fingerprint and continue connecting. """
20 ssh_newkey = 'Are you sure you want to continue connecting'
21 child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
22 i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: '])
25 print 'SSH could not login. Here is what SSH said:'
26 print child.before, child.after
28 if i == 1: # SSH does not have the public key. Just accept it.
29 child.sendline ('yes')
30 child.expect ('password: ')
31 i = child.expect([pexpect.TIMEOUT, 'password: '])
34 print 'SSH could not login. Here is what SSH said:'
35 print child.before, child.after
37 child.sendline(password)
42 host = raw_input('Hostname: ')
43 user = raw_input('User: ')
44 password = getpass.getpass('Password: ')
45 child = ssh_command (user, host, password, '/bin/ls -l')
46 child.expect(pexpect.EOF)
49 if __name__ == '__main__':