Advertisement
Guest User

Untitled

a guest
May 28th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  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, os
  11.  
  12. def ssh_command (user, host, password, command):
  13.  
  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. """
  19.  
  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: '])
  23. if i == 0: # Timeout
  24. print 'ERROR!'
  25. print 'SSH could not login. Here is what SSH said:'
  26. print child.before, child.after
  27. return None
  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: '])
  32. if i == 0: # Timeout
  33. print 'ERROR!'
  34. print 'SSH could not login. Here is what SSH said:'
  35. print child.before, child.after
  36. return None
  37. child.sendline(password)
  38. return child
  39.  
  40. def main ():
  41.  
  42. host = raw_input('Hostname: ')
  43. user = raw_input('User: ')
  44. password = getpass.getpass('Password: ')
  45. child = ssh_command (user, host, password, 'ls -al')
  46. child.expect(pexpect.EOF)
  47. print child.before
  48.  
  49. if __name__ == '__main__':
  50. try:
  51. main()
  52. except Exception, e:
  53. print str(e)
  54. traceback.print_exc()
  55. os._exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement