1

I've been trying to create a script that would back up our switches from a CSV file. I'm using Paramiko to SSH into a switch and run "show run", but for some reason the only output I'm receiving is the name of the switch.

import pandas
import paramiko

# Connection info
USERNAME = "username"
PW = "password"
PORT = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# Backup \ import location
DEST = "C:\\temp\\test\\"
CSV = DEST+"Switches.csv"

device_list = pandas.read_csv(CSV)
for index, row in device_list.iterrows():
    IP = row["IP"]
    floor = row["Floor"]
    side = row["Side"]
    formatted_ip = IP.replace(".", "_")
    filename = f"{formatted_ip}_{floor}{side}.txt"
    ssh.connect(hostname=IP, username=USERNAME, password=PW, port=PORT)
    stdin, stdout, stderr = ssh.exec_command('show running-config')
    stdin.close()
    output = stdout.readlines()
    errors = stderr.read()
    print(output)
    print(stderr.readlines())
    
    outfile = open(DEST + filename, "w")
    for char in output:
        outfile.write(char)
    ssh.close()
    outfile.close()


The output I'm receiving (and also writing into the created file) is SW-3A-48p-4>

I'm able to connect to the switch and run "show run". I'm expecting to get the whole switch configuration but the output stops on the first line.

titors
  • 11
  • 1

1 Answers1

0

As @MarinPrikryl pointed, the devices I was trying to connect do not support the "exec" channel.

Here's how I managed to do it using the shell:

import pandas
import paramiko
from time import sleep

# Connection info
USERNAME = "username"
PW = "password"
PORT = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # I know this isn't recommended, I'll find a better solution for it.

# Backup \ import location
DEST = "C:\\temp\\test\\"
CSV = DEST + "Switches.csv"

device_list = pandas.read_csv(CSV)
for index, row in device_list.iterrows():
    IP = row["IP"]
    floor = row["Floor"]
    side = row["Side"]
    formatted_ip = IP.replace(".", "_")
    filename = f"{formatted_ip}_{floor}{side}.txt"

    ssh.connect(hostname=IP, username=USERNAME, password=PW, port=PORT)
    channel = ssh.invoke_shell()
    stdout = channel.makefile('r')
    channel.send('enable\r\n')
    sleep(1)
    channel.send('terminal length 0\r\n')
    sleep(1)
    channel.send('copy running-config startup-config\r\n')
    sleep(1)
    channel.send('y\r\n')
    sleep(10)
    channel.send('show running-config\r\n')
    sleep(2)

    data = channel.recv(5000)
    data = data.decode("utf8", "ignore")
    data = data.split('show running-config')
    data = data[1][:len(data) - 15]
    outfile = open(DEST + filename, "w")
    for char in data:
        outfile.write(char)
    ssh.close()
    outfile.close()

I'm sure there are better ways to do it, but this works for now. Thanks a lot to everyone who helped.

titors
  • 11
  • 1