Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from paramiko import SSHClient, AutoAddPolicy
- from paramiko.ssh_exception import AuthenticationException
- from getpass import getpass
- class SshClient(object):
- '''
- The Sshclient class wraps some basic
- paramiko.SSHClient functionality
- Attributes:
- host(str): remote host name
- user(str): login user name
- password(str): login user password
- connection(object): the wrapped paramiko.SSHClient
- object or None if the connection is not successful
- '''
- def __init__(self, host, user, pword):
- '''
- The class constructor.
- self.connection is intialized to a paramiko.SSHClient
- instance or None if the connection is not successful.
- Args:
- host(str): remote host name
- user(str): login user name
- pword(str): login user password
- '''
- self.host = host
- self.user = user
- self.password = pword
- self.connection = None
- try:
- self.connection = SSHClient()
- self.connection.set_missing_host_key_policy(AutoAddPolicy())
- self.connection.connect(hostname=host, username=user, password=pword)
- except AuthenticationException as exception:
- print(exception.args)
- self.connection.close()
- self.connection = None
- def execute(self, cmd):
- '''
- Executes a command on the remote host.
- Args:
- cmd(str): the command to be executed
- Returns:
- a dictionary containing the out,
- err and retval keys.
- '''
- stdin, stdout, stderr = self.connection.exec_command(cmd)
- return {'out': stdout.readlines(),
- 'err' : stderr.readlines(),
- 'retval': stdout.channel.recv_exit_status()}
- def close(self):
- '''
- Closes the connection.
- '''
- if not self.connection is None:
- self.connection.close()
- self.connection = None
- if __name__ == '__main__':
- host = input('Remote host name: ')
- user = input('User name: ')
- pword = getpass()
- # connects to the remote client
- # using the given credentials
- try:
- client = SshClient(host, user, pword)
- except exception:
- print(exception.args)
- # if the connection is successful
- # create a directory on the remote host
- # if it does not exist
- if not client.connection is None:
- dir_name = 'my-files'
- list_dirs = 'ls'
- mkdir = 'mkdir ' + dir_name
- msg_dir_exists = 'directory ' + dir_name + ' exists'
- ret = client.execute(list_dirs)
- success = ret['retval'] == 0
- dir_exists = any(dir_name in s for s in ret['out'])
- if success and not dir_exists:
- ret = client.execute(mkdir)
- print(ret['retval'])
- else:
- print(msg_dir_exists)
- client.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement