ssh.py \"Friendly Python SSH2 interface\"


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. """Friendly Python SSH2 interface."""
  2.  
  3. import os
  4. import tempfile
  5. import paramiko
  6.  
  7. class Connection(object):
  8. """Connects and logs into the specified hostname.
  9. Arguments that are not given are guessed from the environment."""
  10.  
  11. def __init__(self,
  12. host,
  13. username = None,
  14. private_key = None,
  15. password = None,
  16. port = 22,
  17. ):
  18. self._sftp_live = False
  19. self._sftp = None
  20. if not username:
  21. username = os.environ['LOGNAME']
  22.  
  23. # Log to a temporary file.
  24. templog = tempfile.mkstemp('.txt', 'ssh-')[1]
  25. paramiko.util.log_to_file(templog)
  26.  
  27. # Begin the SSH transport.
  28. self._transport = paramiko.Transport((host, port))
  29. self._tranport_live = True
  30. # Authenticate the transport.
  31. if password:
  32. # Using Password.
  33. self._transport.connect(username = username, password = password)
  34. else:
  35. # Use Private Key.
  36. if not private_key:
  37. # Try to use default key.
  38. if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
  39. private_key = '~/.ssh/id_rsa'
  40. elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
  41. private_key = '~/.ssh/id_dsa'
  42. else:
  43. raise TypeError, "You have not specified a password or key."
  44.  
  45. private_key_file = os.path.expanduser(private_key)
  46. rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file)
  47. self._transport.connect(username = username, pkey = rsa_key)
  48.  
  49. def _sftp_connect(self):
  50. """Establish the SFTP connection."""
  51. if not self._sftp_live:
  52. self._sftp = paramiko.SFTPClient.from_transport(self._transport)
  53. self._sftp_live = True
  54.  
  55. def get(self, remotepath, localpath = None):
  56. """Copies a file between the remote host and the local host."""
  57. if not localpath:
  58. localpath = os.path.split(remotepath)[1]
  59. self._sftp_connect()
  60. self._sftp.get(remotepath, localpath)
  61.  
  62. def put(self, localpath, remotepath = None):
  63. """Copies a file between the local host and the remote host."""
  64. if not remotepath:
  65. remotepath = os.path.split(localpath)[1]
  66. self._sftp_connect()
  67. self._sftp.put(localpath, remotepath)
  68.  
  69. def execute(self, command):
  70. """Execute the given commands on a remote machine."""
  71. channel = self._transport.open_session()
  72. channel.exec_command(command)
  73. output = channel.makefile('rb', -1).readlines()
  74. if output:
  75. return output
  76. else:
  77. return channel.makefile_stderr('rb', -1).readlines()
  78.  
  79. def close(self):
  80. """Closes the connection and cleans up."""
  81. # Close SFTP Connection.
  82. if self._sftp_live:
  83. self._sftp.close()
  84. self._sftp_live = False
  85. # Close the SSH Transport.
  86. if self._tranport_live:
  87. self._transport.close()
  88. self._tranport_live = False
  89.  
  90. def __del__(self):
  91. """Attempt to clean up if not explicitly closed."""
  92. self.close()
  93.  
  94. def main():
  95. """Little test when called directly."""
  96. # Set these to your own details.
  97. myssh = Connection('example.com')
  98. myssh.put('ssh.py')
  99. myssh.close()
  100.  
  101. # start the ball rolling.
  102. if __name__ == "__main__":
  103. main()

URL: http://commandline.org.uk/forum/topic/420/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.