LittleBizzy

Dominate local SEO with a regional SlickStack cloud server for just $39/month!  Order Now

LEMP Server Update + Upgrade (Cron) Bash Script

One of the most important things to do as a server administrator (“sysadmin”) is keeping the software that is installed on your machine updated and regularly patched for any security issues. Typically, on any Ubuntu server this is done by simply logging in via SSH several times a year (or after any urgent patch is released) and running the following commands:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get autoremove

This set of commands can also be combined, with flags that force “yes” answers to any prompts:

apt-get update && apt-get -y upgrade
apt-get -y autoremove

First, let’s create a new file i.e. ups-cron in which our bash script is going to reside:

Note: you must have root access to your server in order to properly configure this cron job script.

cd /home/example
sudo touch /home/example/ups-cron
sudo nano /home/example/ups-cron

Copy and paste the below script into your newly created file (adjust service names if needed):

Important: notice that sudo is not necessary as we will be adding this shell script to the root user’s crontab. Including sudo in a shell script requires a user’s password to be stored in plaintext = very bad idea!

Code last updated 13 April, 2016

#!/bin/bash
apt-get update && apt-get -y upgrade
apt-get -y autoremove
service nginx restart
service php7.0-fpm restart

Finish up the script by making sure its executable and owned by the root user:

sudo chmod +x /home/example/ups-cron
sudo chown root:root /home/example/ups-cron

You will notice that our script file is merely named “ups-cron” without any file extension, such as .sh or otherwise. This is because we’ve already made the script executable and included a “shebang” line at the top of our script to clarify to the root user which type of script this is (bash), so there is no need for a file extension type.

Lastly, we need to add this script to the root’s crontab file for scheduling:

WARNING: any time you are updating or upgrading a server there is a risk of crashing it, losing important data (i.e. stored in the server’s RAM memory) or causing certain functions to stop working properly. Do not automate this script using a cron job on any production server or client server unless you are fully aware of potential consequences!

sudo crontab -e

At the bottom of the crontab file, paste the below code (change username). /dev/null 2>&1 will prevent any cron reporting attempts being sent via email, which is best in the case that your VPS does not have an active mail server. The below cron job is scheduled to run once every 30 days, which should be more than enough for most servers:

0 0 1 * * /home/example/ups-cron > /dev/null 2>&1
About the Author

Jesse

Leave a Reply

Your email address will not be published. Required fields are marked *