Proxmox VE虚拟机备份脚本

掐指一算发现自己组的软路由已经服役近3年,虽然目前为止都在稳定运行,但是担心哪天这个基于Proxmox VE的"All in boom"设备凉了就得从头配一遍,就写了个小脚本每天备份PVE上的虚拟机,并同时在本地和云端存一份备份。

备份脚本

脚本本体

#!/bin/bash
export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

jobstatus=$1
vmid=$3
vmtype=${VMTYPE} # openvz/qemu
dumpdir=${DUMPDIR}
storeid=${STOREID}
vmname=${HOSTNAME}
tarfile=${TARFILE}
logfile=${LOGFILE}

echo "Job Status: $jobstatus"

if [ "$jobstatus" == "post-restart" ];then
        printf "HOOK-ENV: vmid=$vmid;vmtype=$vmtype;dumpdir=$dumpdir;storeid=$storeid;hostname=$vmname;tarfile=$tarfile;logfile=$logfile\n"
fi

if [ "$jobstatus" == "backup-end" ]; then
        exec   > >(tee -ia $logfile)
        exec  2> >(tee -ia $logfile >& 2)
        exec 19> $logfile
        while :
        do
            let LOOPS+=0
            echo "Retry times: $LOOPS"
            if [[ $LOOPS -gt 5 ]]; then #Set retry count
                break
            fi
            echo "Uploading VM ${vmid}-${vmname} to cloud storage..."
            # Add your upload code here if you want to upload backup files to any cloud storage
        exit 0;
    done
fi

PVE设置

PVE vzdump设置

root@pve:~# cat /etc/vzdump.conf 
# vzdump default settings

#tmpdir: DIR
#dumpdir: DIR
#storage: STORAGE_ID
#mode: snapshot|suspend|stop
#bwlimit: KBPS
#ionice: PRI
#lockwait: MINUTES
#stopwait: MINUTES
#size: MB
#stdexcludes: BOOLEAN
#mailto: ADDRESSLIST
#maxfiles: N
#script: FILENAME
#exclude-path: PATHLIST
#pigz: N
bwlimit: 204800
ionice: 8
maxfiles: 3
mode: snapshot
script: /opt/scripts/pvebackup.sh # Set backup script location

PVE备份任务设置

PVE备份任务设置

PVE邮件告警设置

# 安装依赖
apt-get install libsasl2-modules -y

# 配置告警发件邮箱账号密码
echo "smtp.mailgun.org username@yourdomain.com:passwd" >> /etc/postfix/sasl_passwd
postmap hash:/etc/postfix/sasl_passwd
chmod 600 /etc/postfix/sasl_passwd

# 配置postfix,在/etc/postfix/main.cf中添加以下内容
relayhost = smtp.mailgun.org:465
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sender_dependent_authentication = yes
smtp_generic_maps = hash:/etc/postfix/generic
smtp_use_tls = yes
smtp_tls_wrappermode = yes
smtp_tls_security_level = encrypt
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

# 重新加载postfix配置
postfix reload

# 发信测试
echo "test mail" | mail -s "test mail" target_username@target_domain.com

备份效果

备份效果

备份失败邮件告警示例

备份失败邮件告警示例

我的备份方案

使用本文中的PVE备份脚本产生本地备份,然后传到本地NAS,本地NAS上配置了自动上传到B2云备份。

参考资料

https://pve.proxmox.com/wiki/Backup_and_Restore#_hook_scripts

https://git.proxmox.com/?p=pve-manager.git;a=blob;f=vzdump-hook-script.pl;h=a93eeec80bd09128e70a4a9775438ab658da2191;hb=refs/heads/master