用Python实现网络设备的配置备份
实验目的:在centos8主机上开启FTP server服务,创建python脚本,将SW1~SW5的running configuration 备份保存到TFTP服务器上;
实验准备:
1.在VMware虚拟机安装CentOS 8 的主机,输入下列命令下载安装vsftpd(FTP服务),安装前需要确认主机能否连通外网
yum install vsftpd -y
2.当前启用ftp服务:
systemctl start vsftpd
3.开机自启动ftp服务:
systemctl enable vsftpd
4.确认vsftpd已被启动运行:
systemctl status vsftpd
5.关闭防火墙
systemctl stop firewalld
systemctl status firewalld #查看防火墙被关闭
6.VM创建新用户 #作为ftp用户
useradd -create-home python
passwd python
7.创建ip.txt,放入需要备份的交换机的IP地址
实验代码如下:
import paramiko
import time
import getpass
username = input('Username:')
password = getpass.getpass('password:')
f = open("ip.txt")
for line in f.readlines():
ip_address = line.strip()
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip_address,username=username,password=password,allow_agent=False,look_for_keys=False)
print ("成功连接到", ip_address)
command = ssh_client.invoke_shell()
command.send("configure terminal\n")
command.send("ip ftp username python\n")
command.send("ip ftp password 123\n")
command.send("file prompt quiet\n")
command.send("end\n")
command.send("copy running-config ftp://192.168.0.129\n")
time.sleep(5)
output = command.recv(65535)
print (output.decode('ascii'))
f.close()
ssh_client.close
验证:
运行脚本完毕后,回到/home/python,ls 查看running config是否备份到文件夹下
用cat 打开其中任意一个config文件,验证其内容。