今天要实现两台KEA服务器的配置文件同步。
首先看了一下主备机的服务器配置文件有哪些不同,可以发现,只有两处不同的地方,这样就简单了。
root@AX:/home/keabackup# diff kea-dhcp6-82.conf kea-dhcp6_66.conf
5c5
< "interfaces": ["ens3/2A02:xxxx:0:100::2"]
---
> "interfaces": ["ens3/2A02:xxxx:0:800::2"]
61c61
< "this-server-name": "server1",
---
> "this-server-name": "server2",
那么整个脚本的思路就是这样:
1、取得两台服务器的配置文件(暂时叫A和B)。
2、读取主服务器配置文件A,生成要推送到备机的配置文件C。
3、生成要执行的系统命令,cp 、scp这些。
4、比较C和B文件,如果C文件比较大,就执行系统命令,推送配置到备机。这里因为考虑到配置文件的更新是按照固定模板添加的,文件大小会逐渐增加。
5、成功或失败都写一条日志。
这里用到的知识点有:
文件的读写
日期函数,时间戳和日期
I/O操作
字符串操作
Linux 定时任务
ssh免密登录
下面是python脚本,因为文档所在目录都是固定的,就直接引用绝对目录。预先配置两台服务器之间互相免密登录。
sync-kea.py内容如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import time
import datetime
# 时间戳函数
def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return time.strftime('%Y-%m-%d %H:%M:%S', timeStruct)
# 获取文件大小
def get_FileSize(filePath):
fsize = os.path.getsize(filePath)
fsize = fsize / float(1024 * 1024)
return round(fsize, 2)
# 获取创建时间
def get_FileCreateTime(filePath):
t = os.path.getctime(filePath)
return TimeStampToTime(t)
def Trans_82_66(file_name): # 转换主服务器的配置文件到备份服务器,输出新配置文件
with open(file_name, 'r') as f:
c1 = f.read().replace("2A02:xxxx:0:100", "2A02:xxxx:0:800")
c2 = c1.replace("server1", "server2", 1)
today = datetime.date.today()
todaystr = today.strftime('%Y-%m-%d')
new_file_name = todaystr + '_' + file_name
with open(new_file_name, 'w') as f1:
f1.write(c2)
print("Configuration for KEA backup server is created: ",
new_file_name)
return (new_file_name)
def main():
# 拷贝配置文件到备份文件夹
os.popen(
"cp /usr/local/etc/kea/kea-dhcp6.conf /home/keabackup/kea-dhcp6-82.conf"
).read()
# 抓取备机的配置文件
os.popen(
"scp root@xx.xxx.xxx.66:/usr/local/etc/kea/kea-dhcp6.conf kea-dhcp6_66.conf"
).read()
# 转换配置文件
file_name = "kea-dhcp6-82.conf"
# Trans_82_66(file_name)
# 拷贝转换好的文件到备份服务器
new_file = Trans_82_66(file_name)
# 获得备机配置文件和主机生成的配置文件大小
size1 = get_FileSize('/home/keabackup/kea-dhcp6_66.conf')
size2 = get_FileSize(new_file)
# 生成要执行的命令变量
opcmd = "scp " + new_file + " root@xx.xxx.xxx.66:/home/keabackup/" #当天主机的备份配置
opcmd1 = "scp " + new_file + " root@xx.xxx.xxx.66:/usr/local/etc/kea/kea-dhcp6.conf" #推送到备机的配置文件
if size2 >= size1:
# 如果拷贝成功写入日志
log = 'Successfully Sync dhcp6 configuration from 82 to 66 on ' + TimeStampToTime(time.time()) + '^_^')
os.popen(opcmd).read()
os.popen(opcmd1).read()
print(log)
with open('kea_backup.log', 'a') as f:
print(log, file=f)
else:
print('Something is wrong. ')
with open('kea_backup.log', 'a') as f:
print('Something is wrong! ', 'Not ' + log, file=f)
if __name__ == "__main__":
main()
BTW, 这个脚本运行在主服务器上,另外配置了定时任务,每天凌晨首先把两台服务器的关键文件备份到AWS S3服务器, 再运行同步脚本把主服务器的配置同步到备用服务器上。