{"id":12732,"date":"2019-03-28T15:08:51","date_gmt":"2019-03-28T15:08:51","guid":{"rendered":"http:\/\/www.appservgrid.com\/paw92\/?p=12732"},"modified":"2019-03-28T15:08:51","modified_gmt":"2019-03-28T15:08:51","slug":"using-shell-scripting-to-automate-linux-system-maintenance-tasks","status":"publish","type":"post","link":"https:\/\/www.appservgrid.com\/paw92\/index.php\/2019\/03\/28\/using-shell-scripting-to-automate-linux-system-maintenance-tasks\/","title":{"rendered":"Using Shell Scripting to Automate Linux System Maintenance Tasks"},"content":{"rendered":"<p>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:<\/p>\n<div id=\"attachment_15243\" class=\"wp-caption aligncenter\">\n<p><a href=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Automate-Linux-System-Maintenance-Tasks.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-15243\" src=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Automate-Linux-System-Maintenance-Tasks-620x297.png\" sizes=\"auto, (max-width: 620px) 100vw, 620px\" srcset=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Automate-Linux-System-Maintenance-Tasks-620x297.png 620w, https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Automate-Linux-System-Maintenance-Tasks.png 720w\" alt=\"Automate Linux System Maintenance Tasks\" width=\"620\" height=\"297\" aria-describedby=\"caption-attachment-15243\" data-lazy-loaded=\"true\" \/><\/a><\/p>\n<p id=\"caption-attachment-15243\" class=\"wp-caption-text\">RHCE Series: Automate Linux System Maintenance Tasks \u2013 Part 4<\/p>\n<\/div>\n<p>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,<\/p>\n<p>for example, the tools reviewed in Part 3 \u2013\u00a0<a href=\"https:\/\/www.tecmint.com\/linux-performance-monitoring-and-file-system-statistics-reports\/\" target=\"_blank\" rel=\"noopener\">Monitor System Activity Reports Using Linux Toolsets<\/a>\u00a0of this series. Thus, although he or she may not seem to be doing much, it\u2019s because most of his \/ her responsibilities have been taken care of with the help of shell scripting, which is what we\u2019re going to talk about in this tutorial.<\/p>\n<h3>What is a shell script?<\/h3>\n<p>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.<\/p>\n<p>By default, the shell used for user accounts in\u00a0<strong>RHEL 7<\/strong>\u00a0is bash (<strong>\/bin\/bash<\/strong>). If you want a detailed description and some historical background, you can refer to\u00a0<a href=\"https:\/\/en.wikipedia.org\/wiki\/Bash_%28Unix_shell%29\" target=\"_blank\" rel=\"noopener\">this Wikipedia article<\/a>.<\/p>\n<p>To find out more about the enormous set of features provided by this shell, you may want to check out its\u00a0<strong>man page<\/strong>, which is downloaded in in PDF format at (<a href=\"https:\/\/www.tecmint.com\/wp-content\/pdf\/bash.pdf\" target=\"_blank\" rel=\"noopener\">Bash Commands<\/a>). Other than that, it is assumed that you are familiar with Linux commands (if not, I strongly advise you to go through\u00a0<a href=\"https:\/\/www.tecmint.com\/60-commands-of-linux-a-guide-from-newbies-to-system-administrator\/\" target=\"_blank\" rel=\"noopener\">A Guide from Newbies to SysAdmin<\/a>article in\u00a0<strong>Tecmint.com<\/strong>\u00a0before proceeding). Now let\u2019s get started.<\/p>\n<h3>Writing a script to display system information<\/h3>\n<p>For our convenience, let\u2019s create a directory to store our shell scripts:<\/p>\n<pre># mkdir scripts\r\n# cd scripts\r\n<\/pre>\n<p>And open a new text file named\u00a0<code>system_info.sh<\/code>\u00a0with your preferred text editor. We will begin by inserting a few comments at the top and some commands afterwards:<\/p>\n<pre>#!\/bin\/bash\r\n\r\n# Sample script written for Part 4 of the RHCE series\r\n# This script will return the following set of system information:\r\n# -Hostname information:\r\necho -e \"\\e[31;43m***** <strong>HOSTNAME INFORMATION<\/strong> *****\\e[0m\"\r\nhostnamectl\r\necho \"\"\r\n# -File system disk space usage:\r\necho -e \"\\e[31;43m***** <strong>FILE SYSTEM DISK SPACE USAGE<\/strong> *****\\e[0m\"\r\ndf -h\r\necho \"\"\r\n# -Free and used memory in the system:\r\necho -e \"\\e[31;43m ***** <strong>FREE AND USED MEMORY<\/strong> *****\\e[0m\"\r\nfree\r\necho \"\"\r\n# -System uptime and load:\r\necho -e \"\\e[31;43m***** <strong>SYSTEM UPTIME AND LOAD<\/strong> *****\\e[0m\"\r\nuptime\r\necho \"\"\r\n# -Logged-in users:\r\necho -e \"\\e[31;43m***** <strong>CURRENTLY LOGGED-IN USERS<\/strong> *****\\e[0m\"\r\nwho\r\necho \"\"\r\n# -Top 5 processes as far as memory usage is concerned\r\necho -e \"\\e[31;43m***** <strong>TOP 5 MEMORY-CONSUMING PROCESSES<\/strong> *****\\e[0m\"\r\nps -eo %mem,%cpu,comm --sort=-%mem | head -n 6\r\necho \"\"\r\necho -e \"\\e[1;32mDone.\\e[0m\"\r\n<\/pre>\n<p>Next, give the script execute permissions:<\/p>\n<pre># chmod +x system_info.sh\r\n<\/pre>\n<p>and run it:<\/p>\n<pre>.\/system_info.sh\r\n<\/pre>\n<p>Note that the headers of each section are shown in color for better visualization:<\/p>\n<div id=\"attachment_15238\" class=\"wp-caption aligncenter\">\n<p><a href=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Server-Monitoring-Shell-Script.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-15238\" src=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Server-Monitoring-Shell-Script-556x450.png\" sizes=\"auto, (max-width: 556px) 100vw, 556px\" srcset=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Server-Monitoring-Shell-Script-556x450.png 556w, https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Server-Monitoring-Shell-Script.png 646w\" alt=\"Server Monitoring Shell Script\" width=\"556\" height=\"450\" aria-describedby=\"caption-attachment-15238\" data-lazy-loaded=\"true\" \/><\/a><\/p>\n<p id=\"caption-attachment-15238\" class=\"wp-caption-text\">Server Monitoring Shell Script<\/p>\n<\/div>\n<p>That functionality is provided by this command:<\/p>\n<pre>echo -e \"\\e[<strong>COLOR1;COLOR2m&lt;YOUR TEXT HERE&gt;<\/strong>\\e[0m\"\r\n<\/pre>\n<p>Where\u00a0<strong>COLOR1<\/strong>\u00a0and\u00a0<strong>COLOR2<\/strong>\u00a0are the foreground and background colors, respectively (more info and options are explained in this entry from the\u00a0<a href=\"https:\/\/wiki.archlinux.org\/index.php\/Color_Bash_Prompt\" target=\"_blank\" rel=\"noopener\">Arch Linux Wiki<\/a>) and\u00a0<strong>&lt;YOUR TEXT HERE&gt;<\/strong>\u00a0is the string that you want to show in color.<\/p>\n<h3>Automating Tasks<\/h3>\n<p>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:<\/p>\n<p><strong>1)<\/strong>\u00a0update the local file database, 2) find (and alternatively delete) files with\u00a0<strong>777<\/strong>\u00a0permissions, and\u00a0<strong>3)<\/strong>\u00a0alert when filesystem usage surpasses a defined limit.<\/p>\n<p>Let\u2019s create a file named\u00a0<code>auto_tasks.sh<\/code>\u00a0in our scripts directory with the following content:<\/p>\n<pre>#!\/bin\/bash\r\n\r\n# Sample script to automate tasks:\r\n# -Update local file database:\r\necho -e \"\\e[4;32m<strong>UPDATING LOCAL FILE DATABASE<\/strong>\\e[0m\"\r\nupdatedb\r\nif [ $? == 0 ]; then\r\n        echo \"The local file database was updated correctly.\"\r\nelse\r\n        echo \"The local file database was not updated correctly.\"\r\nfi\r\necho \"\"\r\n\r\n# -Find and \/ or delete files with 777 permissions.\r\necho -e \"\\e[4;32m<strong>LOOKING FOR FILES WITH 777 PERMISSIONS<\/strong>\\e[0m\"\r\n# Enable either option (comment out the other line), but not both.\r\n# Option 1: Delete files without prompting for confirmation. Assumes GNU version of find.\r\n#find -type f -perm 0777 -delete\r\n# Option 2: Ask for confirmation before deleting files. More portable across systems.\r\nfind -type f -perm 0777 -exec rm -i {} +;\r\necho \"\"\r\n# -Alert when file system usage surpasses a defined limit \r\necho -e \"\\e[4;32m<strong>CHECKING FILE SYSTEM USAGE<\/strong>\\e[0m\"\r\nTHRESHOLD=30\r\nwhile read line; do\r\n        # This variable stores the file system path as a string\r\n        FILESYSTEM=$(echo $line | awk '{print $1}')\r\n        # This variable stores the use percentage (XX%)\r\n        PERCENTAGE=$(echo $line | awk '{print $5}')\r\n        # Use percentage without the % sign.\r\n        USAGE=${PERCENTAGE%?}\r\n        if [ $USAGE -gt $THRESHOLD ]; then\r\n                echo \"The remaining available space in $FILESYSTEM is critically low. Used: $PERCENTAGE\"\r\n        fi\r\ndone &lt; &lt;(df -h --total | grep -vi filesystem)\r\n<\/pre>\n<div class=\"google-auto-placed ap_container\">\n<p>Please note that there is a space between the two\u00a0<code>&lt;<\/code>\u00a0signs in the last line of the script.<\/p>\n<div id=\"attachment_15239\" class=\"wp-caption aligncenter\">\n<p><a href=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Shell-Script-to-Find-777-Permissions.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-medium wp-image-15239\" src=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Shell-Script-to-Find-777-Permissions-620x198.png\" sizes=\"auto, (max-width: 620px) 100vw, 620px\" srcset=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Shell-Script-to-Find-777-Permissions-620x198.png 620w, https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Shell-Script-to-Find-777-Permissions.png 674w\" alt=\"Shell Script to Find 777 Permissions\" width=\"620\" height=\"198\" aria-describedby=\"caption-attachment-15239\" data-lazy-loaded=\"true\" \/><\/a><\/p>\n<p id=\"caption-attachment-15239\" class=\"wp-caption-text\">Shell Script to Find 777 Permissions<\/p>\n<\/div>\n<h3>Using Cron<\/h3>\n<p>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\u00a0<strong>cron<\/strong>\u00a0to 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.<\/p>\n<p>The following script (filesystem_usage.sh) will run the well-known\u00a0<strong>df -h<\/strong>\u00a0command, format the output into a HTML table and save it in the\u00a0<strong>report.html<\/strong>\u00a0file:<\/p>\n<pre>#!\/bin\/bash\r\n# Sample script to demonstrate the creation of an HTML report using shell scripting\r\n# Web directory\r\nWEB_DIR=\/var\/www\/html\r\n# A little CSS and table layout to make the report look a little nicer\r\necho \"&lt;HTML&gt;\r\n&lt;HEAD&gt;\r\n&lt;style&gt;\r\n.titulo{font-size: 1em; color: white; background:#0863CE; padding: 0.1em 0.2em;}\r\ntable\r\n{\r\nborder-collapse:collapse;\r\n}\r\ntable, td, th\r\n{\r\nborder:1px solid black;\r\n}\r\n&lt;\/style&gt;\r\n&lt;meta http-equiv='Content-Type' content='text\/html; charset=UTF-8' \/&gt;\r\n&lt;\/HEAD&gt;\r\n&lt;BODY&gt;\" &gt; $WEB_DIR\/report.html\r\n# View hostname and insert it at the top of the html body\r\nHOST=$(hostname)\r\necho \"Filesystem usage for host &lt;strong&gt;$HOST&lt;\/strong&gt;&lt;br&gt;\r\nLast updated: &lt;strong&gt;$(date)&lt;\/strong&gt;&lt;br&gt;&lt;br&gt;\r\n&lt;table border='1'&gt;\r\n&lt;tr&gt;&lt;th class='titulo'&gt;Filesystem&lt;\/td&gt;\r\n&lt;th class='titulo'&gt;Size&lt;\/td&gt;\r\n&lt;th class='titulo'&gt;Use %&lt;\/td&gt;\r\n&lt;\/tr&gt;\" &gt;&gt; $WEB_DIR\/report.html\r\n# Read the output of df -h line by line\r\nwhile read line; do\r\necho \"&lt;tr&gt;&lt;td align='center'&gt;\" &gt;&gt; $WEB_DIR\/report.html\r\necho $line | awk '{print $1}' &gt;&gt; $WEB_DIR\/report.html\r\necho \"&lt;\/td&gt;&lt;td align='center'&gt;\" &gt;&gt; $WEB_DIR\/report.html\r\necho $line | awk '{print $2}' &gt;&gt; $WEB_DIR\/report.html\r\necho \"&lt;\/td&gt;&lt;td align='center'&gt;\" &gt;&gt; $WEB_DIR\/report.html\r\necho $line | awk '{print $5}' &gt;&gt; $WEB_DIR\/report.html\r\necho \"&lt;\/td&gt;&lt;\/tr&gt;\" &gt;&gt; $WEB_DIR\/report.html\r\ndone &lt; &lt;(df -h | grep -vi filesystem)\r\necho \"&lt;\/table&gt;&lt;\/BODY&gt;&lt;\/HTML&gt;\" &gt;&gt; $WEB_DIR\/report.html\r\n<\/pre>\n<div class=\"google-auto-placed ap_container\">\n<p>In our\u00a0<strong>RHEL 7<\/strong>\u00a0server (<strong>192.168.0.18<\/strong>), this looks as follows:<\/p>\n<div id=\"attachment_15241\" class=\"wp-caption aligncenter\">\n<p><a href=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Server-Monitoring-Report.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-15241\" src=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2015\/08\/Server-Monitoring-Report.png\" alt=\"Server Monitoring Report\" width=\"397\" height=\"285\" aria-describedby=\"caption-attachment-15241\" data-lazy-loaded=\"true\" \/><\/a><\/p>\n<p id=\"caption-attachment-15241\" class=\"wp-caption-text\">Server Monitoring Report<\/p>\n<\/div>\n<p>You can add to that report as much information as you want. To run the script every day at\u00a0<strong>1:30 pm<\/strong>, add the following crontab entry:<\/p>\n<pre>30 13 * * * \/root\/scripts\/filesystem_usage.sh\r\n<\/pre>\n<h3>Summary<\/h3>\n<p>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&#8217;t hesitate to add your own ideas or comments via the form below.<\/p>\n<p><a style=\"font-size: 1rem;\" href=\"https:\/\/www.tecmint.com\/using-shell-script-to-automate-linux-system-maintenance-tasks\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/p>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>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: RHCE Series: Automate Linux System Maintenance Tasks \u2013 Part 4 if a sysadmin spends most of his time solving issues &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/www.appservgrid.com\/paw92\/index.php\/2019\/03\/28\/using-shell-scripting-to-automate-linux-system-maintenance-tasks\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Using Shell Scripting to Automate Linux System Maintenance Tasks&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-12732","post","type-post","status-publish","format-standard","hentry","category-linux"],"_links":{"self":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/12732","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/comments?post=12732"}],"version-history":[{"count":1,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/12732\/revisions"}],"predecessor-version":[{"id":12733,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/12732\/revisions\/12733"}],"wp:attachment":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/media?parent=12732"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/categories?post=12732"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/tags?post=12732"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}