1 ftp
因为服务器是linux的,而备份服务器是windows server的,故而采取lftp进行同步文件。
1.1 全量同步
cat > /appdata/script/sync_all.sh <<EOF
#!/bin/bash
# FTP 服务器信息
FTP_SERVER="ftp://192.168.0.5"
FTP_USER="ftp用户名"
FTP_PASS="ftp密码"
FTP_DIR="/mysql_bak"
LOCAL_DIR="/appdata/nfsv/mysql/full"
# 使用 lftp 同步本地目录到远程服务器
lftp -u "$FTP_USER,$FTP_PASS" "$FTP_SERVER" <<EOF
set ftp:passive-mode true # 如果需要,启用被动模式
mirror --reverse --verbose --only-newer $LOCAL_DIR $FTP_DIR
bye
EOF
# 检查 lftp 命令是否成功(注意:这里的 $? 检查的是 lftp 的退出状态)
if [ $? -ne 0 ]; then
echo "Error occurred during FTP sync."
exit 1
fi
echo "FTP sync completed successfully."
EOF
chmod +x /appdata/script/sync_all.sh
1.2 增量同步
cat > /appdata/script/inc_sync.sh <<EOF
#!/bin/bash
MONITOR_DIR="/appdata/nfsv/mysql/full"
DEST_SERVER="192.168.0.5"
DEST_DIR="/mysql_bak"
LFTP_USER="ftp用户名"
LFTP_PASS="ftp密码"
# 创建一个临时文件来保存 lftp 会话命令
LFTP_COMMANDS_FILE=$(mktemp)
LFTP_LOG_FILE=$(mktemp)
# 监听文件变化
inotifywait -r -m -e modify,create,delete,move "$MONITOR_DIR" |
while read path action file; do
# 构建源文件路径
local_file="$path/$file"
# 构建目标文件路径
echo $path
remote_path="$DEST_DIR/${path#$MONITOR_DIR}"
echo $remote_path
remote_file="$remote_path/$file"
echo $remote_file
# 添加 lftp 会话命令到临时文件
echo "open $DEST_SERVER" >> "$LFTP_COMMANDS_FILE"
echo "user $LFTP_USER $LFTP_PASS" >> "$LFTP_COMMANDS_FILE"
echo "cd $DEST_DIR" >> "$LFTP_COMMANDS_FILE"
# 添加 mkdir 命令到 lftp 会话命令文件 (确保目录存在)
echo "mkdir -p '$remote_path'" >> "$LFTP_COMMANDS_FILE"
# 添加 put 命令到 lftp 会话命令文件
echo "cd '$remote_path'" >> "$LFTP_COMMANDS_FILE"
echo "put '$local_file'" >> "$LFTP_COMMANDS_FILE"
echo "cd $DEST_DIR" >> "$LFTP_COMMANDS_FILE" # 返回到初始目录
echo "exit" >> "$LFTP_COMMANDS_FILE"
# 执行 lftp 会话,并将输出重定向到日志文件
lftp -f "$LFTP_COMMANDS_FILE" > "$LFTP_LOG_FILE" 2>&1
# 检查 lftp 输出以获取错误信息
if grep -q "Not connected" "$LFTP_LOG_FILE"; then
echo "Error: Connection not established. Please check the FTP server configuration and network connectivity."
elif grep -q "No such file or directory" "$LFTP_LOG_FILE"; then
echo "Error: Could not create directory. Please check the FTP server permissions."
else
echo "File uploaded successfully."
fi
# 清空 lftp 会话命令文件
> "$LFTP_COMMANDS_FILE"
done
# 清理临时文件
rm "$LFTP_COMMANDS_FILE"
rm "$LFTP_LOG_FILE"
EOF
chmod +x /appdata/script/inc_sync.sh
# windows与linux文件格式存在偏差,可以按照下面的命令进行转换
sed -i 's/\r$//' inc_sync.sh
设置开机启动
cat > /etc/systemd/system/mysql_backup.service <<EOF
[Unit]
Description=MySQL Backup Service
After=network.target
[Service]
Type=simple
ExecStart=/appdata/script/inc_sync.sh
Restart=on-failure
User=root
Group=root
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable mysql_backup
systemctl start mysql_backup