通过python的内置difflib库 比较交换机配置内容的差异,比较结果与代码托管平台类似,将差异部分笔记出来。
环境
1.交换配置SSH登录
2.实验拓扑:
编写代码
- 获取交换机当前配置 file01.txt
- 修改交换机的配置
- 获取交换机修改配置后的信息 file02.txt
- 对比file01.txt 和 file02.txt ,输出对比结果文件 result.html
import difflib
import time
import paramiko
import re
import sys
# 设备信息
ip = '172.16.1.3'
username = 'python'
password = 'Huawei12#$'
# 定义函数获取当前配置
def get_config(ip, username, password):
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, port=22, username=username, password=password)
print(ip+' login successfully')
cli = ssh.invoke_shell()
cli.send('N\n')
time.sleep(0.5)
cli.send('screen-length 0 temporary\n')
time.sleep(0.5)
cli.send('display cur\n')
time.sleep(0.5)
dis_cu = cli.recv(999999).decode()
return (dis_cu)
ssh.close()
# 定义函数ssh_config 将脚本写入配置
def ssh_config(file, ip, username, password):
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, port=22, username=username, password=password)
print(ip+' login successfully')
cli = ssh.invoke_shell()
cli.send('N\n')
time.sleep(0.5)
cli.send('screen-length 0 temporay\n')
time.sleep(0.5)
f = open(file, 'r')
config_list = f.readlines()
for i in config_list:
cli.send(i)
time.sleep(0.5)
dis_this = cli.recv(999999).decode()
ssh.close()
# 调用get_config 赋值给output
output = get_config(ip, username, password)
# 数据处理,使用正则表达式仅获取配置信息
config = re.findall(r'(<ce12800_test>display cu[\d\D]+<ce12800_test>$)', output)
# 保存配置文件file01.txt
with open('file01.txt', 'w') as f:
f.writelines(config[0])
# 修改交换机配置信息;调用ssh_config, 将netconf.txt配置写入设备
ssh_config('netconf.txt', ip, username, password)
# 再次读取配置,保存到本地为file2
output = get_config(ip, username, password)
config = re.findall(r'(<ce12800_test>display cu[\d\D]+<ce12800_test>$)', output) # 这里涉及正则表达式的匹配方式
with open('file02.txt', 'w') as f:
f.writelines(config[0])
# 定义函数读取文件
def read_file(filename):
try:
with open(filename, 'r') as f:
return f.readlines()
except IOError:
print('{} 未找到该文件'.format(filename))
sys.exit(1)
# 定义函数 compare_files 做配置对比, 并保存为result.html
def compare_files(file1, file2, output):
file1_content = read_file(file1)
file2_content = read_file(file2)
d = difflib.HtmlDiff()
result = d.make_file(file1_content, file2_content)
with open(r'result.html', 'w') as f:
f.writelines(result)
print()
# 调用 compare_files
compare_files('file01.txt', 'file02.txt', 'result.html')
实验效果
浏览器打开result.html:
Todo
结合gitlab平台,定时跑脚本,对交换机配置进行比对、备份等