Guest User

Untitled

a guest
Oct 18th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. # Import built-in function
  2.  
  3. # Import third-party pakages
  4. import paramiko
  5.  
  6.  
  7. class SSHConnection(object):
  8. _timeout = 300.0 # connection timeout
  9.  
  10. def __init__(self, **kwargs):
  11. super(SSHConnection, self).__init__()
  12.  
  13. # Note : use '__' to make member as private variable or method that cannot access from outside
  14. self.hostname = kwargs.get("hostname", 'localhost')
  15. self.port = int(kwargs.get('port', '22'))
  16. self.__username = kwargs.get("username", '')
  17. self.__password = kwargs.get("password", '')
  18.  
  19. self.__ssh = paramiko.SSHClient()
  20. self.__ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy) # avoid Exception from missing known_hosts
  21.  
  22. if all(x != '' for x in (self.__username, self.__password)):
  23. self.connect()
  24.  
  25. def connect(self):
  26. self.__ssh.connect(hostname=self.hostname,
  27. port=self.port,
  28. username=self.__username,
  29. password=self.__password,
  30. timeout=self._timeout)
  31. return self.__ssh
  32.  
  33. def runCommand(self, command):
  34. ssh_stdin, ssh_stdout, ssh_stderr = self.__ssh.exec_command("echo %s| sudo -S %s"%(self.__password, command))
  35. print ssh_stdout.read()
  36. print ssh_stderr.read()
  37.  
  38. def close(self):
  39. self.__ssh.close()
  40.  
  41. if __name__ == '__main__':
  42. ssh = SSHConnection(username='user', password='password', hostname='localhost', port = 22)
  43. ssh.runCommand('ls -l /tmp')
  44. ssh.close()
Add Comment
Please, Sign In to add comment