I am trying to connect to two cisco routers by using a JSON file, in paramiko python. Please explain what is wrong with these two files. Start of code
import json
from sys import stdout
from paramiko import *
json_file_object = open('test.json','r ')
List_of_Devices = json.load(json_file_object)
cmd_to_exec = 'show running-config'
for device in List_of_Devices['test']:
output_file_name = str(device['name'] '.txt')
ssh_object = SSHClient()
ssh_object.set_missing_host_key_policy(AutoAddPolicy)
ssh_object.load_host_keys()
ssh_object.connect(device['SSH_IP,SSH_PORT,SSH_USER,SSH_PASSWORD'])
ssh_object.exec_command(cmd_to_exec)
output = stdout.readlines()
file_object = open(output_file_name,'w')
for x in output:
file_object.write(x)
Start of JSON code: is the JSON code format right?
[
{
"HOST_NAME" : "R1",
"SSH_IP" : "192.168.1.2",
"SSH_PORT" : 22,
"SSH_USER" : "wahid",
"SSH_PASSWORD" : "wahid"
},
{
"HOST_NAME" : "R2",
"SSH_IP" : "192.168.1.3",
"SSH_PORT" : 22,
"SSH_USER" : "wahid",
"SSH_PASSWORD" : "wahid"
}
]
End of JSON code:
CodePudding user response:
After discussion in the comments, I wanted to provide an answer to help anyone that may find this question in future.
The first problem I noted was the incorrect passing of parameters to the connect()
method. You needed to use it like so. ssh_object.connect(device["SSH_IP"], device["SSH_PORT"], device["SSH_USER"], device["SSH_PASSWORD"])
.
The second problem you indicated had to do with the need for retrieving STDOUT
. You attempted to use the sys.stdout
library. However paramiko
has a way of retrieving the output from the client. Here's the link for that documentation: Paramiko Client. Below is the adjusted code. You will still need to determine what to do with the output.
import json
from sys import stdout
from paramiko import *
json_file_object = open('test.json','r ')
List_of_Devices = json.load(json_file_object)
cmd_to_exec = 'show running-config'
for device in List_of_Devices['test']:
output_file_name = str(device['name'] '.txt')
ssh_object = SSHClient()
ssh_object.set_missing_host_key_policy(AutoAddPolicy)
ssh_object.load_host_keys()
# Fixed the below line to pass the various parameters you needed.
ssh_object.connect(device["SSH_IP"], device["SSH_PORT"], device["SSH_USER"], device["SSH_PASSWORD"])
# Below changed to obtain the stdout into the std_out variable
std_in, std_out, std_err = ssh_object.exec_command(cmd_to_exec)
# It is possible you will want to be sure std_out is what you expect uncomment the print below to view it.
# print(std_out)
# You should always use a context to wrap a file operation so you don't have to remember to close the file
with open(output_file_name, "w") as file_object:
file_object.write(std_out)