Skip to content

Instantly share code, notes, and snippets.

@YoniItzhak
Last active February 16, 2023 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save YoniItzhak/2daa37485184cfc0b077dd5814c1b20b to your computer and use it in GitHub Desktop.
Save YoniItzhak/2daa37485184cfc0b077dd5814c1b20b to your computer and use it in GitHub Desktop.
Creating connection
from socket import error as socket_error
from fabric import Connection
from paramiko.ssh_exception import AuthenticationException
class ExampleException(Exception): # Should be your Exception
pass
class Host(object):
def __init__(self,
host_ip,
username,
key_file_path):
self.host_ip = host_ip
self.username = username
self.key_file_path = key_file_path
def _get_connection(self):
connect_kwargs = {'key_filename': self.key_file_path}
return Connection(host=self.host_ip, user=self.username, port=22,
connect_kwargs=connect_kwargs)
def run_command(self, command):
try:
with self._get_connection() as connection:
print('Running `{0}` on {1}'.format(command, self.host_ip))
result = connection.run(command, warn=True, hide='stderr')
except (socket_error, AuthenticationException) as exc:
self._raise_authentication_err(exc)
if result.failed:
raise ExampleException(
'The command `{0}` on host {1} failed with the error: '
'{2}'.format(command, self.host_ip, str(result.stderr)))
def put_file(self, local_path, remote_path):
try:
with self._get_connection() as connection:
print('Copying {0} to {1} on host {2}'.format(
local_path, remote_path, self.host_ip))
connection.put(local_path, remote_path)
except (socket_error, AuthenticationException) as exc:
self._raise_authentication_err(exc)
def _raise_authentication_err(self, exc):
raise ExampleException(
"SSH: could not connect to {host} "
"(username: {user}, key: {key}): {exc}".format(
host=self.host_ip, user=self.username,
key=self.key_file_path, exc=exc))
if __name__ == '__main__':
remote_host = Host(host_ip='<host-ip>',
username='<username, e.g. centos>',
key_file_path='path/to/private/key/file')
remote_host.run_command('echo Hello World, I am using Fabric!') # Classic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment