python module paramiko ssh net - ghdrako/doc_snipets GitHub Wiki

pip install paramiko
import paramiko
import time

We need to call the SSHClient function from the paramiko module for the SSH connection. This function is a high-level representation of a session with an SSH server.

client = paramiko.SSHClient()

add untrusted hosts automatically

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

generate connection

client.connect (IP ADDRESS, PORT, USERNAME, PASSWORD)

request an interactive shell session on this channel and assign this function to the commands variable to execute commands on the network devices.

commands = client.invoke_shell ( )

send commands to the device with the send function, and then we use the invoke shell function to do that. nside of the send function, we write the command to run on the device. It sends the command but does not push the Enter button. So, after the command, we must write \n, which goes to the next line in Python programming. Go to the next line means pushing the Enter button. So we send and run the commands on the devices:

commands.send ("COMMAND \n")

it takes time to display the output; it’s not instant. So, we should add a delay after the line that we send the command to the device. We can collect the entire output with this delay. If we did not add any time delays, some parts of the logs might not have been collected.

time.sleep(1)  # 1s wait

Finally, after we send the command to the device, we need to receive some output. We collect the outputs with the Recv() function. This function gets the data from the currently active channel. If we write 20 as a nbytes value, the code contains only the first 20 characters in the output.

NBYTE=1.000.000
output = commands.recv ( NBYTES ) # 

the received data format is in nbytes, so we need to change it to a human-readable format as UTF-8 with the decode function.

output = output.decode ( "utf-8" )
print (output)