python批量生成配置
# 读取data.txt文件
with open('data.txt', 'r') as data_file:
data_lines = data_file.readlines()
# 读取template.txt文件
with open('template.txt', 'r') as template_file:
template_content = template_file.read()
# 使用split()函数将data.txt的文件分割为二维数组
data_array = [line.strip().split() for line in data_lines]
result = '' # 保存结果的变量
prev_first_column = None # 前一个循环的第一列数据
# 遍data.txt的二维数组的每行
for row in data_array:
first_column = row[0] # 当前行的一列数据
# 判断是否需要添加当前行的第一列和第二数据到结果中
if first_column != prev_first_column:
result += f'\n\n{row[0]} {row[1]}\n'
# 替换template.txt的占位符
placeholders = ['%{}%'.format(i - 1) for i in range(2, len(row))]
print(placeholders)
replacements = row[2:]
print(replacements)
temp = template_content
for placeholder, replacement in zip(placeholders, replacements):
temp = temp.replace(placeholder, replacement)
# print(template_content)
result += temp + '\n' # 将替换后的数据添加到结果中
prev_first_column = first_column # 更新前一个循环的第一列数据
# 将结果输出到txt文件
with open('output.txt', 'w') as output_file:
output_file.write(result)
data.txt文件格式:
1.1.1.1 sw1 gi0/1
1.1.1.1 sw1 gi0/2
1.1.1.1 sw1 gi0/3
1.1.1.2 sw2 gi0/1
1.1.1.2 sw2 gi0/2
1.1.1.2 sw2 gi0/3
template.txt格式
interface %1%
shutdown
exit
output.txt格式
1.1.1.1 sw1
interface gi0/1
shutdown
exit
interface gi0/2
shutdown
exit
interface gi0/3
shutdown
exit
1.1.1.2 sw2
interface gi0/1
shutdown
exit
interface gi0/2
shutdown
exit
interface gi0/3
shutdown
exit