I am trying to port all the powershell based QA automation scripts to python. I was using plink to send ssh commands to the targets, mainly cisco switches and store output to a text file and then generate an html report with selected output from the text file. It seems paramiko is the favorite of all when it comes to ssh via python.
Here I want to share a post on how easy it is achieve this.
First let us define the variables which we will be using.
target = '10.1.1.1 #cisco nexus 9000
username = 'admin' #username
password = ‘@dmin' #password
command = 'show run' #command to run
and the rest of the stuff which does the actual work is
import paramiko #import paramiko module
ssh = paramiko.SSHClient() #create an ssh client
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #auto accept ssh key
ssh.connect(target, port=22, username=username, password=password) #connect to the target
stdin, stdout, stderr = ssh.exec_command(command) #execute the command
output = stdout.readlines() #get the output
outstore = '\n'.join(output) #format the output to print each line in a new line
print output #print output
I have added the description against each line for you to understand what and how does it work.
If you have many commands for which you want the output then just go ahead and create an array and run a loop against that array. If you want the output to be written to a text file then modify the last line accordingly. I hope this is enough to get you started.
The code is somewhere here https://github.com/MrAmbiG/python