Module “Paramiko” is a python implementation of SSH v2 i.e. if we have any requirement of accessing a host via SSH; This module must be used.
We primarily use “paramiko” for login into the devices and run some commands.
Connecting to a Remote Host
Refer to below code snippet
import paramiko
DEVICE_IP = '10.120.235.166'
USERNAME = 'admin'
PASSWORD = 'Nvidia@557'
# Lets create an Object SSH
SSH = paramiko.SSHClient()
try:
SSH.connect(DEVICE_IP,port=22,username=USERNAME,password=PASSWORD)
except paramiko.SSHException:
print('SSH ERROR', paramiko.SSHException)
else:
print('SSH is successful to device ', + DEVICE_IP)
If we execute this; we will get an error as below
Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3296, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-5-27d441bf6606>", line 1, in <module> SSH.connect(DEVICE_IP,port=22,username=USERNAME,password=PASSWORD) File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\client.py", line 416, in connect self, server_hostkey_name, server_key File "C:\ProgramData\Anaconda3\lib\site-packages\paramiko\client.py", line 824, in missing_host_key "Server {!r} not found in known_hosts".format(hostname) paramiko.ssh_exception.SSHException: Server '10.120.235.166' not found in known_hosts
We get an error; It is basically an exception that says that “server_key” is not found in known_hosts because it is missing in missing_host_key. There may be the instances where we might not want to trust the host and python default behavior is to Reject.
In “paramiko” there are actually two policies
1. paramiko “Reject” policy – Default one as shown above
2. paramiko “Auto-add” policy – Automatically accepting all and added them to the Host file.
Lets override the default policy behavior with “Auto-add” policy as shown below
import paramiko
DEVICE_IP = '10.120.235.166'
USERNAME = 'admin'
PASSWORD = 'Nvidia@557'
# Lets create an Object SSH
SSH = paramiko.SSHClient()
# Lets override the default policy behavior
SSH.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
SSH.connect(DEVICE_IP,port=22,username=USERNAME,password=PASSWORD)
except paramiko.SSHException:
print('SSH ERROR', paramiko.SSHException)
else:
print('SSH is successful to device ' + DEVICE_IP)
Refer for output
$ python demo_paramiko.py SSH is successful to device 10.120.235.166
You can observe that our connection is successful which can also be seen from device terminal
sw1-server.ban-in#show user Line User Host(s) Idle Location * 2 vty 0 gaagrawal idle 00:00:00 10.24.71.57
Let’s add more complexity i.e. we want to track following scenario in SSH connection.
- Authentication failed due to wrong Username/Password
- Network Connectivity issue
- SSH timeout
Refer to this snipped to track above real-time issues
import paramiko
import socket
DEVICE_IP = '10.10.10.10'
USERNAME = 'gaagrawal'
PASSWORD = 'Kanika!88'
# Lets create an Object SSH
SSH = paramiko.SSHClient()
# Lets override the default policy behavior
SSH.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
SSH.connect(DEVICE_IP,port=22,username=USERNAME,password=PASSWORD)
except paramiko.AuthenticationException:
print("Authentication failed, please verify your credential")
except paramiko.SSHException:
print("Could not establish SSH connection: %s" % paramiko.SSHException)
except Exception as TimeoutError:
print("Unable to connect, please verify network connectivity")
except socket.timeout as e:
print("Connection got timed out")
else:
print('SSH is successful to device ' + DEVICE_IP)
Executing some commands on Remote Host
Now, we are connected to the remote server. The next step is to execute commands on the SSH server. To run a command on the server the exec_command() function is called on the SSHClient with the command passed as input. When you execute commands using exec_command a new Channel is opened and the requested command is executed. The response is returned as Python file-like objects representing stdin, stdout, and stderr(as a 3-tuple)
- The stdin is a write-only file which can be used for input commands.
- The stdout file give the output of the command.
- The stderr gives the errors returned on executing the command. Will be empty if there is no error.
import paramiko
import socket
DEVICE_IP = '10.24.3.4'
USERNAME = 'gaagrawal'
PASSWORD = 'Kanika!88'
COMMAND = 'show etherchannel summary'
# Lets create an Object SSH
SSH = paramiko.SSHClient()
# Lets override the default policy behavior
SSH.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
SSH.connect(DEVICE_IP,port=22,username=USERNAME,password=PASSWORD)
except paramiko.AuthenticationException:
print("Authentication failed, please verify your credential")
except paramiko.SSHException:
print("Could not establish SSH connection: %s" % paramiko.SSHException)
except Exception as TimeoutError:
print("Unable to connect, please verify network connectivity")
except socket.timeout as e:
print("Connection got timed out")
else:
print('SSH is successful to device ' + DEVICE_IP)
stdin, stdout, stderr = SSH.exec_command(COMMAND, timeout=10)
SSH.ssh_output = stdout.readlines()
SSH.ssh_error = stderr.readlines()
if SSH.ssh_error:
print("Problem occurred while running command:" + COMMAND + " The error is " + SSH.ssh_error)
else:
print("Command execution completed successfully")
print('\n'.join(SSH.ssh_output))
Closing SSH connection
As a best practice; once our Job is done with SSH connection – It is advised to close the connection. This can be achieved using “SSH.close()”