Nov 13, 2022

Anacron and Mail Backup

Recently I am trying to backup my server's mail content to my local laptop with Anacron. So here is a short note on how to do it.

Mail backup

With my mail server configuration and SSH as root I put together a Makefile relatively quickly:

all: deploy deploy: rsync -azv -e 'ssh -A -J $(USER)@$(SERVER)' root@127.0.0.1:/var/mail/vmail/zhtluo.com ./

Anacron Setup

Put the script (named as mail-backup) to /etc/cron.daily:

#!/bin/sh set -e # Backup mails sudo -u zhtluo -- bash -p -c 'cd /home/zhtluo/mail-backup && make'

Set the correct privilege:

sudo chmod 755 mail-backup

Verify that it works:

sudo run-parts --test /etc/cron.daily
/etc/cron.daily/0anacron /etc/cron.daily/apport /etc/cron.daily/apt-compat /etc/cron.daily/cracklib-runtime /etc/cron.daily/dpkg /etc/cron.daily/logrotate /etc/cron.daily/mail-backup /etc/cron.daily/man-db

Optional: Configure an e-mail Report

Anacron reports with sendmail by default. We need to configure a client if we want to have it deliver the report to us.

Install msmtp:

sudo apt install msmtp msmtp-mta

Configure /etc/msmtprc:

# Set default values for all following accounts. defaults # Use the mail submission port 587 instead of the SMTP port 25. port 587 # Always use TLS. tls on # Set a list of trusted CAs for TLS. The default is to use system settings, but # you can select your own file. tls_trust_file /etc/ssl/certs/ca-certificates.crt # The SMTP server account local host zhtluo.com from local@zhtluo.com set_from_header on user local@zhtluo.com domain zhtluo.com auth on # TODO: Replace here with your password password replaceme # Set default account account default: local # Map local users to mail addresses aliases /etc/aliases

Note: It is not the best way to keep plain password in the file, but I did not find a good alternative. See also the documentation.

Add MAILTO to /etc/anacrontab:

# /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh HOME=/root LOGNAME=root MAILTO=local@zhtluo.com # These replace cron's entries 1 5 cron.daily run-parts --report /etc/cron.daily 7 10 cron.weekly run-parts --report /etc/cron.weekly @monthly 15 cron.monthly run-parts --report /etc/cron.monthly

Make sure everything works:

sudo anacron -fnd