]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - third_party/Python/module/pexpect-2.4/examples/sshls.py
Vendor import of lldb trunk r290819:
[FreeBSD/FreeBSD.git] / third_party / Python / module / pexpect-2.4 / examples / sshls.py
1 #!/usr/bin/env python
2
3 """This runs 'ls -l' on a remote host using SSH. At the prompts enter hostname,
4 user, and password.
5
6 $Id: sshls.py 489 2007-11-28 23:40:34Z noah $
7 """
8
9 import pexpect
10 import getpass
11 import os
12
13
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. """
20
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: '])
24     if i == 0:  # Timeout
25         print 'ERROR!'
26         print 'SSH could not login. Here is what SSH said:'
27         print child.before, child.after
28         return None
29     if i == 1:  # SSH does not have the public key. Just accept it.
30         child.sendline('yes')
31         child.expect('password: ')
32         i = child.expect([pexpect.TIMEOUT, 'password: '])
33         if i == 0:  # Timeout
34             print 'ERROR!'
35             print 'SSH could not login. Here is what SSH said:'
36             print child.before, child.after
37             return None
38     child.sendline(password)
39     return child
40
41
42 def main():
43
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)
49     print child.before
50
51 if __name__ == '__main__':
52     try:
53         main()
54     except Exception as e:
55         print str(e)
56         traceback.print_exc()
57         os._exit(1)