提问人:titors 提问时间:11/8/2022 更新时间:11/8/2022 访问量:351
Python - 尝试使用 Paramiko 备份网络交换机,未收到预期输出 [重复]
Python - Trying to backup a network switch using Paramiko, not receiving the expected output [duplicate]
问:
我一直在尝试创建一个脚本,该脚本将从CSV文件备份我们的交换机。 我正在使用 Paramiko 通过 SSH 连接到交换机并运行“show run”,但由于某种原因,我收到的唯一输出是交换机的名称。
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()
我收到的输出(也写入创建的文件)是SW-3A-48p-4>
我能够连接到交换机并运行“show run”。 我期望获得整个交换机配置,但输出在第一行停止。
答:
0赞
titors
11/8/2022
#1
正如@MarinPrikryl指出的,我尝试连接的设备不支持“exec”通道。
以下是我如何使用 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()
我确信有更好的方法可以做到这一点,但这目前有效。 非常感谢所有帮助过的人。
评论