网站搜索

使用 Shell 脚本自动化 Linux 系统维护任务 - 第 4 部分


前段时间我读到,有效的系统管理员/工程师的显着特征之一就是懒惰。乍一看似乎有点矛盾,但作者随后解释了原因:

如果系统管理员将大部分时间花在解决问题和执行重复性任务上,您可能会怀疑他或她做得不太正确。换句话说,一个有效的系统管理员/工程师应该制定一个计划,以尽可能少的操作来执行重复性任务,并且应该通过使用来预见问题,

例如,本系列第 3 部分 – 使用 Linux 工具集监控系统活动报告中介绍的工具。因此,虽然他或她可能看起来没有做太多事情,但这是因为他/她的大部分职责都是在 shell 脚本的帮助下完成的,这就是我们将在本教程中讨论的内容。

什么是 shell 脚本?

简而言之,shell脚本只不过是由shell逐步执行的程序,它是在Linux内核和最终用户之间提供接口层的另一个程序。

默认情况下,RHEL 7 中用户帐户使用的 shell 是 bash (/bin/bash)。如果你想要详细的描述和一些历史背景,你可以参考这篇维基百科文章。

要了解有关此 shell 提供的大量功能的更多信息,您可能需要查看其手册页,该手册页以 PDF 格式在 (Bash Commands) 下载。除此之外,假设您熟悉 Linux 命令(如果不熟悉,我强烈建议您在继续之前阅读 Howtoing.com 中的新手到系统管理员指南文章)。现在让我们开始吧。

编写脚本显示系统信息

为了方便起见,我们创建一个目录来存储 shell 脚本:


mkdir scripts
cd scripts

然后使用您喜欢的文本编辑器打开一个名为 system_info.sh 的新文本文件。我们将首先在顶部插入一些注释,然后插入一些命令:


#!/bin/bash

Sample script written for Part 4 of the RHCE series
This script will return the following set of system information:
-Hostname information:
echo -e "\e[31;43m***** HOSTNAME INFORMATION *****\e[0m"
hostnamectl
echo ""
-File system disk space usage:
echo -e "\e[31;43m***** FILE SYSTEM DISK SPACE USAGE *****\e[0m"
df -h
echo ""
-Free and used memory in the system:
echo -e "\e[31;43m ***** FREE AND USED MEMORY *****\e[0m"
free
echo ""
-System uptime and load:
echo -e "\e[31;43m***** SYSTEM UPTIME AND LOAD *****\e[0m"
uptime
echo ""
-Logged-in users:
echo -e "\e[31;43m***** CURRENTLY LOGGED-IN USERS *****\e[0m"
who
echo ""
-Top 5 processes as far as memory usage is concerned
echo -e "\e[31;43m***** TOP 5 MEMORY-CONSUMING PROCESSES *****\e[0m"
ps -eo %mem,%cpu,comm --sort=-%mem | head -n 6
echo ""
echo -e "\e[1;32mDone.\e[0m"

接下来,授予脚本执行权限:


chmod +x system_info.sh

并运行它:


./system_info.sh

请注意,每个部分的标题都以颜色显示,以便更好地可视化:

该功能由以下命令提供:


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

其中 COLOR1COLOR2 分别是前景色和背景色(更多信息和选项在 Arch Linux Wiki 的这个条目中进行了解释)和 <您的文本在这里> 是您想要以颜色显示的字符串。

自动化任务

您可能需要自动化的任务可能因情况而异。因此,我们不可能在一篇文章中涵盖所有可能的场景,但我们将介绍三个可以使用 shell 脚本自动化的经典任务:

1) 更新本地文件数据库,2) 查找(或者删除)具有 777 权限的文件,以及3) 在文件系统使用率超过时发出警报一个明确的限制。

让我们在脚本目录中创建一个名为 auto_tasks.sh 的文件,其中包含以下内容:


#!/bin/bash

Sample script to automate tasks:
-Update local file database:
echo -e "\e[4;32mUPDATING LOCAL FILE DATABASE\e[0m"
updatedb
if [ $? == 0 ]; then
        echo "The local file database was updated correctly."
else
        echo "The local file database was not updated correctly."
fi
echo ""

-Find and / or delete files with 777 permissions.
echo -e "\e[4;32mLOOKING FOR FILES WITH 777 PERMISSIONS\e[0m"
Enable either option (comment out the other line), but not both.
Option 1: Delete files without prompting for confirmation. Assumes GNU version of find.
#find -type f -perm 0777 -delete
Option 2: Ask for confirmation before deleting files. More portable across systems.
find -type f -perm 0777 -exec rm -i {} +;
echo ""
-Alert when file system usage surpasses a defined limit 
echo -e "\e[4;32mCHECKING FILE SYSTEM USAGE\e[0m"
THRESHOLD=30
while read line; do
        # This variable stores the file system path as a string
        FILESYSTEM=$(echo $line | awk '{print $1}')
        # This variable stores the use percentage (XX%)
        PERCENTAGE=$(echo $line | awk '{print $5}')
        # Use percentage without the % sign.
        USAGE=${PERCENTAGE%?}
        if [ $USAGE -gt $THRESHOLD ]; then
                echo "The remaining available space in $FILESYSTEM is critically low. Used: $PERCENTAGE"
        fi
done < <(df -h --total | grep -vi filesystem)

请注意,脚本最后一行的两个 < 符号之间有一个空格。

使用计划任务

为了进一步提高效率,您将不想坐在计算机前手动运行这些脚本。相反,您将使用 cron 安排这些任务定期运行,并通过电子邮件将结果发送给预定义的收件人列表,或将它们保存到可以使用 Web 浏览器查看的文件中。

以下脚本 (filesystem_usage.sh) 将运行众所周知的 df -h 命令,将输出格式化为 HTML 表并将其保存在 report.html 文件中:


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

在我们的 RHEL 7 服务器 (192.168.0.18) 中,如下所示:

您可以向该报告添加任意数量的信息。要每天下午 1:30 运行脚本,请添加以下 crontab 条目:


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

概括

您很可能会想到您想要或需要自动化的其他几项任务;正如您所看到的,使用 shell 脚本将大大简化这项工作。如果您认为本文有帮助,请随时告诉我们,并随时通过下面的表格添加您自己的想法或评论。