Become a Member to receive automatic updates and support for our 50+ WordPress plugins!250,000+ sites use our WP plugins!  Click Here

LEMP Server Update + Upgrade (Cron) Bash Script

   |  13 Apr, 2016

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

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

Tags: , , , , ,

Last modified:  23 Jul, 2016