Friday, March 20, 2015

Automate Debian system updates using Crontab

Updating a Debian system is as easy as executing the following command as root:

# apt-get update && apt-get upgrade

If you have a sudo account, run the command like this:

$ sudo apt-get update && sudo apt-get upgrade

Instead of running the command interactively, you can automate the manual update process by running a cron job. Below, I assume you login as root.

Run the following command to create or edit your cron jobs. Note that the default text editor is opened automatically for you to enter the cron jobs.

# crontab -e

As an example, I will schedule the update to happen daily at 2am. I entered the following line as my first (failed) attempt.

00 02 * * * apt-get update 2>&1 && apt-get -y upgrade 2>&1

A typical upgrade usually prompts you to confirm a transaction before it is executed. Because the cron upgrade is non-interactive, I specify the -y parameter to tell apt-get to assume yes for all prompts.

At 2am, the above command executed, and failed with the following errors:

debconf: unable to initialize frontend: Dialog   
debconf: (TERM is not set, so the dialog frontend is not usable.)    
debconf: falling back to frontend: Readline   
debconf: unable to initialize frontend: Readline   
debconf: (This frontend requires a controlling tty.)   
debconf: falling back to frontend: Teletype  
dpkg-preconfigure:unable to re-open stdin: Fetched 49.5 MB in 17s (2,840 kB/s)  
dpkg: warning: 'ldconfig' not found in PATH or not executable  
dpkg: warning: 'start-stop-daemon' not found in PATH or not executable  
dpkg: error: 2 expected programs not found in PATH or not executable  
Note: root's PATH should usually contain /usr/local/sbin, /usr/sbin and /sbin  
E: Sub-process /usr/bin/dpkg returned an error code (2)

There were 2 problems. First, a front-end was expected, but there was none. Second, the PATH for locating commands was not set up correctly.

To correct the problems, re-run crontab -e, and insert the following lines to properly set up the run-time environment.

DEBIAN_FRONTEND=noninteractive  
PATH=/usr/sbin:/usr/bin:/sbin:/bin  
00 02 * * * apt-get update 2>&1 && apt-get -y upgrade 2>&1

Automating the system update process saves you time, and keep your system more up-to-date as a protection against potential cyber attacks. If you are interested in Debian system administration, please see What to do after spinning up a Debian VPS.

2 comments:

  1. I would like to point out that there are specific tools for this in Debian. Namely unattended-upgrades and optionally needrestart (in jessie or wheezy-backports). They create a cron job that is specifically designed to handle these situations and is able to send mail reports. Also, apticron can be used to only notify of updates instead.

    ReplyDelete
  2. Thanks for the information and links you shared this is so should be a useful and quite informative!
    startup jobs

    ReplyDelete