Exercise

Backing Up /etc Nightly Exercise

Task

Back up /etc every night at 10 p.m. as root, copying each snapshot to another host so it is not lost with the machine. servera is a server that never sleeps, so a system crontab in /etc/cron.d/ is the right home for the job.

Hosts
servera, with workstation holding the copy
Back up
/etc
Snapshot to
workstation:/tmp
Runs as
root
Schedule
every night at 10 p.m.
  1. Write the backup script on servera

    Become root, because everything here is system-wide.

    sudo -i
    vim /usr/local/bin/etc_backup.sh

    Give it a hashbang and name the destination host once in a variable.

    #!/bin/bash
    backup_host="workstation"
    scp -r /etc "student@${backup_host}:/tmp/$(hostname)_etc_$(date --iso-8601=minutes)"

    Make it executable and run it once by hand, then check the copied directory on workstation.

    chmod a+x /usr/local/bin/etc_backup.sh
    /usr/local/bin/etc_backup.sh
    ssh student@workstation 'ls -ld /tmp/servera.lab.example.com_etc_*'
    ssh student@workstation 'ls -l /tmp/servera.lab.example.com_etc_*/passwd'
  2. Schedule it in /etc/cron.d

    Copy /etc/crontab as a starting point. You get the field reference in the comments and leave the original untouched.

    cp /etc/crontab /etc/cron.d/backups
    vim /etc/cron.d/backups

    Press G for the last line and o to open one below it. Add a test schedule that runs every minute:

    * * * * * root etc_backup.sh
  3. Find out why nothing happened

    Wait for the next minute, then look for a new snapshot.

    ssh student@workstation 'ls -ld /tmp/servera.lab.example.com_etc_*'
    grep etc_backup /var/log/cron

    No new snapshot, and the log says why:

    CROND[...]: (root) CMD (etc_backup.sh)
    CROND[...]: (root) CMDOUT (/bin/bash: line 1: etc_backup.sh: command not found)

    Fix it with an absolute path. Press G, then C to replace the line:

    vim /etc/cron.d/backups
    * * * * * root /usr/local/bin/etc_backup.sh
  4. Confirm root ran it, then set the real schedule

    Wait another minute, then check the log and the offsite copy on workstation.

    grep etc_backup /var/log/cron
    ssh student@workstation 'ls -ld /tmp/servera.lab.example.com_etc_*'
    ssh student@workstation 'ls -l /tmp/servera.lab.example.com_etc_*/passwd'

    The log names the user the job ran as:

    CROND[12124]: (root) CMD (/usr/local/bin/etc_backup.sh)
    CROND[12123]: (root) CMDEND (/usr/local/bin/etc_backup.sh)

    It works, so give it the schedule you actually want. Press G and cc again:

    vim /etc/cron.d/backups
    0 22 * * * root /usr/local/bin/etc_backup.sh
    tail -1 /etc/cron.d/backups
  5. Clean up

    Remove the schedule and script on servera and the copied directories on workstation, then leave the root shell.

    rm -f /etc/cron.d/backups /usr/local/bin/etc_backup.sh
    ssh student@workstation 'sudo rm -rf /tmp/servera.lab.example.com_etc_*'
    ls /etc/cron.d/
    exit