Issue
In order to connect via SSH I'm using the following code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(IP, username=USER, password=PSW,look_for_keys=False)
my question is, how can I handle a missing connection? In particular I'd like that in case the connection is not established the code goes (maybe with a GOTO?) to another point of the code where basically I restart the server.
Solution
You could simply use a try and catch the exception as mentioned by martin-prikryl, such as:
try:
client.connect(host="192.168.0.8",
username="user1",
password="password1234"
)
except AuthenticationException:
print("Authentication failed, please verify your credentials: %s")
except SSHException as sshException:
print("Unable to establish SSH connection: %s" % sshException)
For other examples of ssh exceptions you can look at https://www.programcreek.com/python/example/7495/paramiko.SSHException
Answered By - Nuzvee Answer Checked By - Marilyn (WPSolving Volunteer)