Using Shell Scripting to Automate Linux System Maintenance Tasks – Part 4

[‘

n

Some time ago I read that one of the distinguishing characteristics of an effective system administrator / engineer is laziness. It seemed a little contradictory at first but the author then proceeded to explain why:

n

Automate Linux System Maintenance Tasks
RHCE Series: Automate Linux System Maintenance Tasks – Part 4

n

if a sysadmin spends most of his time solving issues and doing repetitive tasks, you can suspect he or she is not doing things quite right. In other words, an effective system administrator / engineer should develop a plan to perform repetitive tasks with as less action on his / her part as possible, and should foresee problems by using,

n

for example, the tools reviewed in Part 3 – Monitor System Activity Reports Using Linux Toolsets of this series. Thus, although he or she may not seem to be doing much, it’s because most of his / her responsibilities have been taken care of with the help of shell scripting, which is what we’re going to talk about in this tutorial.

n

What is a shell script?

n

In few words, a shell script is nothing more and nothing less than a program that is executed step by step by a shell, which is another program that provides an interface layer between the Linux kernel and the end user.

n

By default, the shell used for user accounts in RHEL 7 is bash (/bin/bash). If you want a detailed description and some historical background, you can refer to this Wikipedia article.

n

To find out more about the enormous set of features provided by this shell, you may want to check out its man page, which is downloaded in in PDF format at (Bash Commands). Other than that, it is assumed that you are familiar with Linux commands (if not, I strongly advise you to go through A Guide from Newbies to SysAdmin article in Tecmint.com before proceeding). Now let’s get started.

n

Writing a script to display system information

n

For our convenience, let’s create a directory to store our shell scripts:

n

# mkdir scriptsrn# cd scriptsrn

n

And open a new text file named system_info.sh with your preferred text editor. We will begin by inserting a few comments at the top and some commands afterwards:

n

#!/bin/bashrnrn# Sample script written for Part 4 of the RHCE seriesrn# This script will return the following set of system information:rn# -Hostname information:rnecho -e "\e[31;43m***** HOSTNAME INFORMATION *****\e[0m"rnhostnamectlrnecho ""rn# -File system disk space usage:rnecho -e "\e[31;43m***** FILE SYSTEM DISK SPACE USAGE *****\e[0m"rndf -hrnecho ""rn# -Free and used memory in the system:rnecho -e "\e[31;43m ***** FREE AND USED MEMORY *****\e[0m"rnfreernecho ""rn# -System uptime and load:rnecho -e "\e[31;43m***** SYSTEM UPTIME AND LOAD *****\e[0m"rnuptimernecho ""rn# -Logged-in users:rnecho -e "\e[31;43m***** CURRENTLY LOGGED-IN USERS *****\e[0m"rnwhornecho ""rn# -Top 5 processes as far as memory usage is concernedrnecho -e "\e[31;43m***** TOP 5 MEMORY-CONSUMING PROCESSES *****\e[0m"rnps -eo %mem,%cpu,comm --sort=-%mem | head -n 6rnecho ""rnecho -e "\e[1;32mDone.\e[0m"rn

n

Next, give the script execute permissions:

n

# chmod +x system_info.shrn

n

and run it:

n

./system_info.shrn

n

Note that the headers of each section are shown in color for better visualization:

n

Server Monitoring Shell Script
Server Monitoring Shell Script

n

That functionality is provided by this command:

n

echo -e "\e[COLOR1;COLOR2m<YOUR TEXT HERE>\e[0m"rn

n

Where COLOR1 and COLOR2 are the foreground and background colors, respectively (more info and options are explained in this entry from the Arch Linux Wiki) and <YOUR TEXT HERE> is the string that you want to show in color.

n

Automating Tasks

n

The tasks that you may need to automate may vary from case to case. Thus, we cannot possibly cover all of the possible scenarios in a single article, but we will present three classic tasks that can be automated using shell scripting:

n

1) update the local file database, 2) find (and alternatively delete) files with 777 permissions, and 3) alert when filesystem usage surpasses a defined limit.

n

Let’s create a file named auto_tasks.sh in our scripts directory with the following content:

n

#!/bin/bashrnrn# Sample script to automate tasks:rn# -Update local file database:rnecho -e "\e[4;32mUPDATING LOCAL FILE DATABASE\e[0m"rnupdatedbrnif [ $? == 0 ]; thenrn        echo "The local file database was updated correctly."rnelsern        echo "The local file database was not updated correctly."rnfirnecho ""rnrn# -Find and / or delete files with 777 permissions.rnecho -e "\e[4;32mLOOKING FOR FILES WITH 777 PERMISSIONS\e[0m"rn# Enable either option (comment out the other line), but not both.rn# Option 1: Delete files without prompting for confirmation. Assumes GNU version of find.rn#find -type f -perm 0777 -deletern# Option 2: Ask for confirmation before deleting files. More portable across systems.rnfind -type f -perm 0777 -exec rm -i {} +;rnecho ""rn# -Alert when file system usage surpasses a defined limit rnecho -e "\e[4;32mCHECKING FILE SYSTEM USAGE\e[0m"rnTHRESHOLD=30rnwhile read line; dorn        # This variable stores the file system path as a stringrn        FILESYSTEM=$(echo $line | awk '{print $1}')rn        # This variable stores the use percentage (XX%)rn        PERCENTAGE=$(echo $line | awk '{print $5}')rn        # Use percentage without the % sign.rn        USAGE=${PERCENTAGE%?}rn        if [ $USAGE -gt $THRESHOLD ]; thenrn                echo "The remaining available space in $FILESYSTEM is critically low. Used: $PERCENTAGE"rn        firndone < n

Please note that there is a space between the two < signs in the last line of the script.

n
Shell Script to Find 777 Permissions
Shell Script to Find 777 Permissions
n

Using Cron

n

To take efficiency one step further, you will not want to sit in front of your computer and run those scripts manually. Rather, you will use cron to schedule those tasks to run on a periodic basis and sends the results to a predefined list of recipients via email or save them to a file that can be viewed using a web browser.

n

The following script (filesystem_usage.sh) will run the well-known df -h command, format the output into a HTML table and save it in the report.html file:

n
#!/bin/bashrn# Sample script to demonstrate the creation of an HTML report using shell scriptingrn# Web directoryrnWEB_DIR=/var/www/htmlrn# A little CSS and table layout to make the report look a little nicerrnecho "<HTML>rn<HEAD>rn<style>rn.titulo{font-size: 1em; color: white; background:#0863CE; padding: 0.1em 0.2em;}rntablern{rnborder-collapse:collapse;rn}rntable, td, thrn{rnborder:1px solid black;rn}rn</style>rn<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />rn</HEAD>rn<BODY>" > $WEB_DIR/report.htmlrn# View hostname and insert it at the top of the html bodyrnHOST=$(hostname)rnecho "Filesystem usage for host <strong>$HOST</strong><br>rnLast updated: <strong>$(date)</strong><br><br>rn<table border='1'>rn<tr><th class='titulo'>Filesystem</td>rn<th class='titulo'>Size</td>rn<th class='titulo'>Use %</td>rn</tr>" >> $WEB_DIR/report.htmlrn# Read the output of df -h line by linernwhile read line; dornecho "<tr><td align='center'>" >> $WEB_DIR/report.htmlrnecho $line | awk '{print $1}' >> $WEB_DIR/report.htmlrnecho "</td><td align='center'>" >> $WEB_DIR/report.htmlrnecho $line | awk '{print $2}' >> $WEB_DIR/report.htmlrnecho "</td><td align='center'>" >> $WEB_DIR/report.htmlrnecho $line | awk '{print $5}' >> $WEB_DIR/report.htmlrnecho "</td></tr>" >> $WEB_DIR/report.htmlrndone < <(df -h | grep -vi filesystem)rnecho "</table></BODY></HTML>" >> $WEB_DIR/report.htmlrn

n

In our RHEL 7 server (192.168.0.18), this looks as follows:

n

Server Monitoring Report
Server Monitoring Report

n

You can add to that report as much information as you want. To run the script every day at 1:30 pm, add the following crontab entry:

n

30 13 * * * /root/scripts/filesystem_usage.shrn

n

Summary

n

You will most likely think of several other tasks that you want or need to automate; as you can see, using shell scripting will greatly simplify this effort. Feel free to let us know if you find this article helpful and don't hesitate to add your own ideas or comments via the form below.

n

‘]