Every day I run a rsync job that transfers backups between two servers. The job is a two-part cronjob. As seen below:
30 23 * * * /home/<user>/rsync.sh >/dev/null 2>&1 0 6 * * * killall rsync >/dev/null 2>&1;
The job starts at 11:30pm and is killed at 6am. The script that it calls does the following:
#!/bin/bash find /var/log/rsync/ -mtime +8 |xargs -I % sh -c 'rm -f %'; find /var/log/rsync/log.* |xargs -I % sh -c 'tar -rf /var/log/rsync/rsync.1.tar %; rm -f %'; rsync --bwlimit=1050 --protect-args --delete --size-only --copy-dirlinks --log-file=/var/log/rsync/log.`date +"%Y%m%d_%H%M%S"` -avP -e "ssh -T -o Compression=no -x" "/path/to/files/" "<user>@domain:/path/to/files/";
Basically it removed old logs, putting them into a nice tarball which it will delete periodically. Then it runs the backup script, creating a new log. Generally, I will log in peridocally and manually check the logs to make sure everything is working as it should. What I want to to do, simply, is to have it email the contents of the log every day, saving me the 30 seconds trouble of logging in and checking manually.
As I have a ‘proper’ mail server with SMTP/IMAP I want to us it to send the logs.
Installing and Configuring Packages:
sudo apt install mailutils ssmtp
Configure ssmtp by editing the main config file: /etc/ssmtp/ssmtp.conf. Comment out all the other lines so your configuration looks like this:
mailhub=mailserver.domain.com:587 UseSTARTTLS=YES AuthUserfirstname.lastname@example.org AuthPass=password
You will need to have configured a mail user on your mail server. All users will send from the email@example.com address. This isn’t a problem as the only mail I’m sending from this server are alerts and logs. In server environments where there are multiple users sending general mail this setup will not be appropriate.
Next, edit the revaliases file in the same directory. Add the details for the user who will be running the command to send email:
That’s the configuration done!
Test sending an email with the following:
echo "this is a test" | mail -s "Test Email" firstname.lastname@example.org
Check the contents of the syslog:
:~$ tail -3 /var/log/syslog Sep 26 08:47:21 servername sSMTP: Creating SSL connection to host Sep 26 08:47:22 servername sSMTP: SSL connection using RSA_AES_128_CBC_SHA1 Sep 26 08:47:25 servername sSMTP: Sent mail for email@example.com (221 2.0.0 Bye) uid=1000 username=localuser outbytes=4792
Automate sending the logs:
Change the crontab file with:
Add the email command to the end of the job that kills the process:
30 23 * * * /home/wargus/rsync.sh >/dev/null 2>&1 0 6 * * * killall rsync >/dev/null 2>&1; cat /var/log/rsync/log* | mail -s "Rsync Log for `date`" firstname.lastname@example.org