Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Import built-in function
- # Import third-party pakages
- import paramiko
- class SSHConnection(object):
- _timeout = 300.0 # connection timeout
- def __init__(self, **kwargs):
- super(SSHConnection, self).__init__()
- # Note : use '__' to make member as private variable or method that cannot access from outside
- self.hostname = kwargs.get("hostname", 'localhost')
- self.port = int(kwargs.get('port', '22'))
- self.__username = kwargs.get("username", '')
- self.__password = kwargs.get("password", '')
- self.__ssh = paramiko.SSHClient()
- self.__ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy) # avoid Exception from missing known_hosts
- if all(x != '' for x in (self.__username, self.__password)):
- self.connect()
- def connect(self):
- self.__ssh.connect(hostname=self.hostname,
- port=self.port,
- username=self.__username,
- password=self.__password,
- timeout=self._timeout)
- return self.__ssh
- def runCommand(self, command):
- ssh_stdin, ssh_stdout, ssh_stderr = self.__ssh.exec_command("echo %s| sudo -S %s"%(self.__password, command))
- print ssh_stdout.read()
- print ssh_stderr.read()
- def close(self):
- self.__ssh.close()
- if __name__ == '__main__':
- ssh = SSHConnection(username='user', password='password', hostname='localhost', port = 22)
- ssh.runCommand('ls -l /tmp')
- ssh.close()
Add Comment
Please, Sign In to add comment