Comprehensive Linux Daily Inspection Bash Script for System Health Monitoring
This article provides a complete Bash script that performs daily health checks on a Linux host, gathering information on disk usage, memory, CPU, processes, services, network configuration, user accounts, password policies, firewall, SELinux, NTP, SNMP, JDK, and more, then formats the results into a report and emails it.
The script is designed to run on a Linux server (tested on CentOS) and generate a daily health‑check report covering a wide range of system metrics. It first ensures it runs as root, sets a proper PATH, and determines the host's IP address.
Global Variables
Several variables are declared to store report fields such as date, hostname, OS release, kernel version, language, uptime, CPU details, memory statistics, disk and inode usage, network settings, SELinux status, firewall status, user information, password expiry, sudoers count, SSH configuration, and service counts.
Core Functions
version : Prints the script version.
getCpuStatus : Uses /proc/cpuinfo to count physical and logical CPUs, cores per CPU, CPU model, and architecture, then stores the values.
getMemStatus : Retrieves total and free memory from /proc/meminfo, calculates used memory and usage percentage, and records the results.
getDiskStatus : Calls df -hTP and df -iTP to collect disk space and inode usage, computes totals, free space, and usage percentages.
getSystemStatus : Gathers OS release, kernel, hostname, SELinux status, last reboot time, uptime, and sets the locale.
getServiceStatus : Lists enabled services and running services (using systemctl on CentOS 7+ or chkconfig / service on older versions) and records their counts.
getAutoStartStatus : Counts lines in /etc/rc.d/rc.local that are not comments, representing custom auto‑start programs.
getLoginStatus : Shows recent login entries via last.
getNetworkStatus : Displays network interfaces, default gateway, DNS servers, and records IP, MAC, gateway, and DNS values.
getListenStatus : Lists TCP listening sockets with ss -ntul and counts distinct ports.
getCronStatus : Enumerates user crontabs and files under /etc/cron*, summing the total number of scheduled jobs.
getUserStatus : Reports /etc/passwd modification time, lists root users, all users, users with empty passwords, and users sharing the same UID.
getPasswordStatus : Checks password expiration for each user, reports never‑expire or days until expiry, and extracts password policy parameters from /etc/login.defs.
getSudoersStatus : Counts non‑comment lines in /etc/sudoers.
getInstalledStatus : Shows recently installed RPM packages.
getProcessStatus : Detects defunct (zombie) processes and lists top memory‑consuming and CPU‑consuming processes.
getJDKStatus : Prints Java version and JAVA_HOME.
getSyslogStatus : Reports the state of the rsyslog service and displays its configuration file.
getFirewallStatus : Checks the status of iptables (or firewalld on newer systems) and shows the firewall rules file.
getSNMPStatus : Reports the state of the snmpd service and shows its configuration.
getNTPStatus : Reports the state of the ntpd service and displays /etc/ntp.conf if present.
getSSHStatus : Shows SSH daemon status, protocol version, whether root login is permitted, and counts authorized keys for each user.
getchage_file_24h : Finds recently modified script, ASP, PHP, ASPX, JSP, HTML files and other system changes within the last 24 hours.
uploadHostDailyCheckReport : Packages all collected variables into a JSON payload and posts it to a predefined API endpoint.
check : Calls all the above functions in order to build the full report.
Execution Flow
The script ends by invoking check > $RESULTFILE, which writes the formatted output to a file named HostDailyCheck-<em>IP</em>-<em>date</em>.txt. It then emails the report using mail with a subject indicating an "Alibaba Cloud PHP Enterprise Platform Inspection Report".
Key Points
All environment variables are explicitly exported to avoid missing commands when the script runs from cron.
Conditional logic handles differences between CentOS 6 and CentOS 7+ for service management.
Report fields are stored in variables prefixed with report_ and later assembled into JSON for remote ingestion.
The script is intended to be run daily via cron to provide continuous monitoring.
#!/bin/bash
# @Author: HanWei
# @Date: 2020-03-16 09:56:57
# @Last Modified by: HanWei
# @Last Modified time: 2020-03-16 11:06:31
# @E-mail: [email protected]
# 主机信息每日巡检
IPADDR=$(ifconfig eth0|grep 'inet addr'|awk -F '[ :]' '{print $13}')
export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
source /etc/profile
[ $(id -u) -gt 0 ] && echo "请用root用户执行此脚本!" && exit 1
centosVersion=$(awk '{print $(NF-1)}' /etc/redhat-release)
VERSION="2020-03-16"
# ... (rest of the functions as described above) ...
check > $RESULTFILE
echo "检查结果:$RESULTFILE"
mail -a $RESULTFILE -s "阿里云PHP企业平台巡检报告" [email protected]Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
