#!/bin/bash
# 指定目标主机备份文件路径
backup_file="/home/rancher/cluster.yml"
# 指定远程目标备份路径
backup_dir="/data/k8s/qingcloud/pre/auth/"
# 指定远程备份文件名
remote_backup_file="$backup_dir/$(basename "$backup_file")"
# 指定备份主机的IP地址
backup_host="10.x.x.x"
# 企业微信备份通知
qiwei_notify() {
# 企业微信机器人的 Webhook 地址
webhook_url="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=e5554-518b-4ec8-8415-58xxxxxxb41"
# 获取本机的 IP 地址
ip_address=$(ip addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}')
# 消息内容,包括备份文件变化和本机 IP 地址
message="监测到 $ip_address 的 $backup_file 变化,进行备份。"
# 发送消息请求
curl -H "Content-Type: application/json" -X POST -d '{"msgtype": "text", "text": {"content": "'"$message"'"},"safe":0}' $webhook_url
}
# 检测备份文件是否有变化
if [[ $(stat -c %Y "$backup_file") -gt $(ssh "root@$backup_host" stat -c %Y $remote_backup_file 2>/dev/null || echo 0) ]]; then
echo "Backup file has changed. Performing backup..."
# 获取当前时间戳
timestamp=$(date +%Y%m%d%H%M%S)
# 将远程主机文件重命名
ssh "root@$backup_host" "if [ -f '$remote_backup_file' ]; then mv '$remote_backup_file' '${remote_backup_file}_$timestamp'; fi"
# 执行备份操作,将备份文件复制到远程目录,并使用新的文件名
scp "$backup_file" "root@$backup_host:$backup_dir" && qiwei_notify
echo "Backup completed."
else
echo "Backup file has not changed."
fi