Created
March 24, 2021 05:37
-
-
Save isaidnocookies/3eab2819a5c73b9a4602b33f737c6bbf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from paramiko import SSHClient, AutoAddPolicy, RSAKey | |
from paramiko.auth_handler import AuthenticationException, SSHException | |
from pathlib import Path | |
class SSHer(): | |
def __init__(self, remote_host, user, key_path): | |
self.remote_host = remote_host | |
self.ssh_key_path = key_path | |
self.user = user | |
self.client = None | |
def disconnect(self): | |
if self.client != None: | |
self.client.close() | |
self.client = None | |
def connect(self): | |
try: | |
if self.client is not None and self.client.get_transport() is not None: | |
if self.client.get_transport().is_active(): | |
return | |
except Exception as error: | |
print(error) | |
if self.client is None: | |
try: | |
key = RSAKey.from_private_key_file(self.ssh_key_path) | |
self.client = SSHClient() | |
self.client.set_missing_host_key_policy(AutoAddPolicy()) | |
self.client.connect( | |
hostname=self.remote_host, | |
username=self.user, | |
pkey=key | |
) | |
except Exception as error: | |
print (error) | |
else: | |
self.client.close() | |
self.client = None | |
self.connect() | |
def sendCommand(self, command): | |
self.connect() | |
deployCommand = '{}'.format(command) | |
stdin, stdout, stderr = self.client.exec_command(deployCommand) | |
stdout.channel.recv_exit_status() | |
return response | |
ssher = SSHer("localhost") | |
ssher.connect() | |
response = ssher.sendCommand("ls") | |
ssher.disconnect() | |
print (response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment