服务器中的备份脚本

服务器中的备份脚本

我正在使用 Ubuntu 12.10 服务器版本,现在我需要一个脚本来将 Samba 共享备份到连接到服务器的 USB 驱动器,并生成包含文件名、大小和时间的日志文件格式的备份日志

还要确认 Crontab 设置

提前致谢

答案1

如果你还没有安装,rsync请安装它们

sudo apt-get install rsync

创建脚本backup_script.sh

#!/bin/bash

# Script to backup personal files to the external USB drive.
# Specify the mount point here (DO NOT end mount_point with a forward-slash).
mount_point='/mnt/'

echo "#####"
echo ""
# Check whether target volume is mounted, and mount it if not.
if ! mountpoint -q ${mount_point}/; then
    echo "Mounting the external USB drive."
    echo "Mountpoint is ${mount_point}"
    if ! mount ${mount_point}; then
        echo "An error code was returned by mount command!"
        exit 5
    else echo "Mounted successfully.";
    fi
else echo "${mount_point} is already mounted.";
fi
# Target volume **must** be mounted by this point. If not, die screaming.
if ! mountpoint -q ${mount_point}/; then
    echo "Mounting failed! Cannot run backup without backup volume!"
    exit 1
fi

echo "Preparing to transfer differences using rsync."

# Use the year to create a new backup directory each year.
current_year=`date +%Y`
# Now construct the backup path, specifying the mount point followed by the path
# to our backup directory, finishing with the current year.
# (DO NOT end backup_path with a forward-slash.)
backup_path=${mount_point}'/rsync-backup/'${current_year}

echo "Backup storage directory path is ${backup_path}"

echo "Starting backup of /home/XXX/Pictures . . . "
mkdir --parents ${backup_path}/Pictures
# This time use the -a flag with the tee command, so that it appends to the end
# of the rsync-output.txt file rather than start a new file from scratch.
sudo rsync --archive --verbose --human-readable --itemize-changes --progress --no-o --no-g \
--delete --delete-excluded \
/home/XXX/Pictures/ ${backup_path}/Pictures/ 2>&1 | tee -a /home/XXX/rsync-output.txt


echo ""
echo "####"

你必须改变

  • 您的扩展 USB 的挂载点 - 例如我使用/mnt/
  • 您希望备份的文件夹路径 - 例如我使用/home/XXX/Pictures
  • 写入日志文件的地方-例如我使用/home/XXX/

赋予脚本执行权限

chmod +x /path_to_script/backup_script.sh

设置crontab为每x隔一段时间运行此命令

用于编辑crontab运行

crontab -e

每 5 分钟运行一次命令的代码是

*/5 * * * * /path_to_script/backup_script.sh

每小时

0 */1 * * * /path_to_script/backup_script.sh

凌晨 4 点跑步

0 4 * * * /path_to_script/backup_script.sh

您也可以使用命令将日志文件发送到您的邮箱

mail -s "SMB backup" [email protected] < /path_to_log/rsync-output.txt

设置 cron 来为你执行

0 4 * * * mail -s "SMB backup" [email protected] < /path_to_log/rsync-output.txt

答案2

您可以使用不同的软件包进行备份。我个人使用rsnapshot封装了 的软件包rsync

这里有一些配置文件,您可以在其中指定您的所有愿望。

相关内容