[Python][Paramiko] Simple class for ssh operations
1 min readJan 15, 2020
Paramiko is a wonderful module that can be used to perform ssh operations through python programs. Here I am introducing a simple python class that can help ease few ssh operations that we come across in our daily tasks.
class RemoteConnect:
def __init__(self,host):
self.host = host
self.client = None
self.scp = None
self.__connect()
def __connect(self):
try:
self.client = SSHClient()
self.client.load_system_host_keys()
self.client.set_missing_host_key_policy(AutoAddPolicy())
self.client.connect(hostname=self.host,
username=USERNAME,
key_filename=KEY)
self.scp = SCPClient(self.client.get_transport())
except AuthenticationException as error:
print('Authentication Failed: Please check your network/ssh key')
finally:
return self.client
def disconnect(self):
self.client.close()
self.scp.close() def exec_command(self,command):
if self.client is None:
self.client == self.__connect()
stdin,stdout,stderr = self.client.exec_command(command)
status = stdout.channel.recv_exit_status()
if status is 0:
return stdout.read()
else:
return None
def transfer(self,file,remotepath):
try:
if self.client is None:
self.client = self.__connect()
self.scp.put(file,
remotepath,
recursive=True)
except SCPException as error:
print('SCPException: Failed transferring data')
Try out this class and add your valuable comments, so I can make this class much better.
Thanks for reading. Have a great day !!