I am trying to create a Python application that establish a SSH command and sends a few commands.
At the moment, I am at the step where I just want to open a SSH connection, send a pwd command, and disconnect from the session.
This is the code I did so far:
import paramiko
class Host:
"""This class represents the SSH connection to a host.
It has attributes related to the remote host being connected and the state of the SSH connection."""
def __init__(self, remote_host, login, password):
self.remote_host = remote_host
self.login = login
self.password = password
self.ssh_client = None # Fix Variable Before Assignment Warning.
def connect(self):
try:
# Try to connect and handle errors - Instantiating an object of the class, not a local object.
self.ssh_client = paramiko.SSHClient() # Self instantiates the object, not local.
self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Try for only 1 second.
self.ssh_client.connect(self.remote_host, username=self.login, password=self.password, timeout=1)
# Multiple Assignment / Data Unpacking
# stdin, stdout, stderr = ssh_client.exec_command('pwd')
# response_stdout = stdout.read().decode().strip()
return "Connected to SSH!"
except paramiko.ssh_exception.SSHException as ssh_exception:
return f"SSHException - Failed to connect to the host: {ssh_exception}"
except TimeoutError as timeout_error:
return f"TimeoutError - Host unavailable: {timeout_error}"
# finally:
# ssh_client.close()
def isconnected(self):
if self.ssh_client:
return self.ssh_client
else:
return None
def disconnect(self):
# Use the object attribute that represents the connection state to disconnect.
if self.ssh_client is not None:
self.ssh_client.close()
return "Disconnected from SSH!"
else:
return "No active SSH connection."
Now, what I expected was the following flow:
--- Connect to SSH (Retain Connection Open) ----
--- Do something ... Maybe a PWD or something ----
--- Close the SSH Connection ---
But for some reason, when calling:
print("Testing SSH Connection.")
host = Host("192.168.1.10", 'administrator', 'SuperStrongP477')
if host.isconnected():
print("SSH Connected.")
else:
print("SSH Not Connected.")
I get:
Testing SSH Connection. SSH Not Connected.
I already looked into other posts but they did not help me, since I did not understand clearly how to adapt it to my code... The answers I looked up and did not help, were:
execute git command in a remote machine using paramiko How to keep ssh session not expired using paramiko? Execute multiple commands in Paramiko so that commands are affected by their predecessors
Those two did clarify some doubts but I still was not able to implement their solutions into my own code.