您不必running-config
通过 TFTP 传输。您需要做的就是在您的 PC/服务器上创建一个文件并将其保存到您已经创建的文件夹中。
在某些操作系统 (Windows) 上,:
文件夹或文件名中不允许使用冒号 ( )。请避免使用它。
这与您想要实现的目标类似:
import os
import time
from datetime import datetime
import paramiko
TNOW = datetime.now().replace(microsecond=0)
TFORMAT = TNOW.strftime("%d-%m-%Y_%H:%M:%S")
target_dir = "tftpdata/Region1/"
today = target_dir + time.strftime("%Y-%m-%d")
now = TNOW.strftime("%H:%M:%S")
if not os.path.isdir(today): # Changed to os.path.isdir
os.makedirs(today)
print(f"\nCreated {today} folder successfully", today)
else:
print(f"\n{today} folder already exists!")
username = "cisco"
password = "cisco"
DEVICE_LIST = open("iplist")
for RTR in DEVICE_LIST:
RTR = RTR.strip()
print(f"\n#### Connecting to the device {RTR} ####\n")
SESSION = paramiko.SSHClient()
SESSION.set_missing_host_key_policy(paramiko.AutoAddPolicy())
SESSION.connect(
RTR,
port=22,
username=username,
password=password,
look_for_keys=False,
allow_agent=False,
)
# Used `exec_command` instead of `send`
stdin, stdout, stderr = SESSION.exec_command("show running-config")
with open(f"{today}/{RTR}-running-config.txt", "w") as outfile:
outfile.write(str(stdout.read().decode("utf-8")))
print(f"Backup completed for the {RTR}\n")
SESSION.close()
DEVICE_LIST.close() # Don't forget to close the iplist file
甚至我的代码的更好版本是:
import os
from datetime import date
import paramiko
today = date.today()
target_dir = f"tftpdata/Region1/{today}"
# Check if the target directory is created
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
print(f"\nCreated {target_dir} folder successfully")
else:
print(f"\n{target_dir} folder already exists!")
# Username and password
usr = "developer"
pwd = "C1sco12345"
# Read `iplist.txt` and create a list of IP Addresses
with open("iplist.txt", "r") as iplist:
DEVICE_LIST = [ip for ip in iplist.read().splitlines()]
for DEVICE in DEVICE_LIST:
print(f"\n#### Connecting to {DEVICE} ####\n")
# Use `with` statement (Context Manager) to automatically close the connection
with paramiko.SSHClient() as SESSION:
SESSION.set_missing_host_key_policy(paramiko.AutoAddPolicy())
SESSION.connect(
DEVICE,
port=22,
username=usr,
password=pwd,
look_for_keys=False,
allow_agent=False,
)
# Sending command by `exec_command`
stdin, stdout, stderr = SESSION.exec_command("show running-config")
with open(f"{target_dir}/{DEVICE}-running-config-{today}.txt", "w") as outfile:
outfile.write(stdout.read().decode("utf-8").lstrip().replace("\n", ""))
print(f"Backup completed for {DEVICE}\n")
更新
由于 switch 类型是sg300
,并且它已经在netmiko
. netmiko
使用如下所示做同样的事情:
import csv
import os
from datetime import date
from netmiko import ConnectHandler
today = date.today()
target_dir = f"tftpdata/Region1/{today}"
# Check if the target directory is created
if not os.path.isdir(target_dir):
os.makedirs(target_dir)
print(f"\nCreated {target_dir} folder successfully")
else:
print(f"\n{target_dir} folder already exists!")
# Username and password
usr = "developer"
pwd = "C1sco12345"
# Read `iplist.csv` and create a list of IP Addresses
# Notice here iplist is a CSV file not text file
with open(file="iplist.csv", mode="r") as iplist:
reader = csv.reader(iplist)
DEVICE_LIST = [
{
"device_type": "cisco_s300",
"ip": ip.strip(),
"username": usr,
"password": pwd,
"fast_cli": False,
}
for ip in iplist
]
for DEVICE in DEVICE_LIST:
print(f'\n#### Connecting to {DEVICE["ip"]} ####\n')
with ConnectHandler(**DEVICE) as ssh_conn:
# You don't need to send `terminal length 0`. netmiko handles this for you
running_config = ssh_conn.send_command("show running-config")
with open(
f'{target_dir}/{DEVICE["ip"]}-running-config-{today}.txt', "w"
) as outfile:
outfile.write(running_config.lstrip())
print(f'Backup completed for {DEVICE["ip"]}\n')
和iplist.csv