Question

I am using paramiko to login to a list of devices and then run a list of commands on each device and then capture the output. The python script is as follows:

import paramiko

f1 = open('hostfile','r')
f2 = open('commandfile','r')

devices = f1.readlines()
commands = f2.readlines()


for device in devices:
    for command in commands:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(device, username="admin", password="test")
        stdin, stdout, stderr = ssh.exec_command(command)
        output= stdout.read()

f1.close()
f2.close()

What I want to achieve is to store the entire output in a 2 dimensional array as follows:

data = [
('device1', 'output1 for device1', 'output2 for device1', 'output3 for device1'),
('device2', 'output1 for device2', 'output2 for device2', 'output3 for device2'),
('device3', 'output1 for device3', 'output2 for device3', 'output3 for device3')
   ..................
   .................
]

I need to pass this output to an excel sheet using xlwt and hence my need to store the output in this format..

Was it helpful?

Solution

Is this what you want?

data = []
for device in devices:
    data.append([device])
    for command in commands:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(device, username="admin", password="test")
        stdin, stdout, stderr = ssh.exec_command(command)
        output= stdout.read()
        data[-1].append(output)
    data[-1] = tuple(data[-1])

Some explanation:

what data[-1] and tuple(data[-1]) actually do

Note that data is supposed to be a list of tuples.

  1. data[-1] refers to the last item of the list data.

  2. data[-1] is built as a list in the inner loop. As your specified output structure of data is a list of tuples, the code uses the function tuple() to get a tuple converted from the list data[-1].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top