Operations 10 min read

Automate Linux Daily System Checks with a Comprehensive Bash Script

This article presents a ready‑to‑use Bash script that performs daily Linux system inspections—including disk, memory, CPU, process, file changes, and user login checks—generates a detailed report, saves it under a log directory, and emails the results for easy monitoring.

Open Source Linux
Open Source Linux
Open Source Linux
Automate Linux Daily System Checks with a Comprehensive Bash Script

This article provides a ready‑to‑use Bash script for daily Linux system inspection. The script checks a wide range of items such as disk usage, memory status, CPU information, running processes, file modifications, and user login activity, then compiles the findings into a report that is emailed and stored locally.

The script begins by setting necessary environment variables, ensuring it runs as root, and determining the host IP address. It creates a log directory if it does not exist and defines a result file named HostDailyCheck-<IP>-$(date +%Y%m%d).txt. Global variables are declared to hold report fields like hostname, OS release, kernel version, uptime, CPU details, memory statistics, disk and inode usage, network configuration, SELinux status, firewall status, user accounts, password policies, and service information.

Key functions include:

getCpuStatus : Retrieves physical and logical CPU counts, core numbers, CPU model, and architecture, then stores the data in report variables.

getMemStatus : Obtains total and free memory, calculates used memory and usage percentage, and records the values.

getDiskStatus : Uses df to collect disk and inode statistics, computes totals, free space, and usage percentages, and saves them to the report.

getSystemStatus : Gathers system information such as OS type, release version, kernel, hostname, SELinux state, language/encoding, current time, last reboot time, and uptime.

getServiceStatus : (Content omitted for brevity) Intended to inspect running services, sudoers, SSH configuration, and other security‑related settings.

After defining these functions, the script can be invoked manually or scheduled via cron to run automatically each day. The final report is written to the result file and can be sent via email using standard mail utilities.

#!/bin/bash
# @Author: HanWei
# @Date:   2021-08-25 13:56:57
# @Last Modified by:   HanWei
# @Last Modified time: 2021-08-25 23:53: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"

# Log setup
PROGPATH=$(echo $0 | sed -e 's,[\/][^\/][^\/]*$,,' )
[ -f $PROGPATH ] && PROGPATH="."
LOGPATH="$PROGPATH/log"
[ -e $LOGPATH ] || mkdir $LOGPATH
RESULTFILE="$LOGPATH/HostDailyCheck-$IPADDR-$(date +%Y%m%d).txt"

# Global report variables
report_DateTime=""
report_Hostname=""
report_OSRelease=""
report_Kernel=""
report_Language=""
report_LastReboot=""
report_Uptime=""
report_CPUs=""
report_CPUType=""
report_Arch=""
report_MemTotal=""
report_MemFree=""
report_MemUsedPercent=""
report_DiskTotal=""
report_DiskFree=""
report_DiskUsedPercent=""
report_InodeTotal=""
report_InodeFree=""
report_InodeUsedPercent=""
report_IP=""
report_MAC=""
report_Gateway=""
report_DNS=""
report_Listen=""
report_Selinux=""
report_Firewall=""
report_USERs=""
report_USEREmptyPassword=""
report_USERTheSameUID=""
report_PasswordExpiry=""
report_RootUser=""
report_Sudoers=""
report_SSHAuthorized=""
report_SSHDProtocolVersion=""
report_SSHDPermitRootLogin=""
report_DefunctProsess=""
report_SelfInitiatedService=""
report_SelfInitiatedProgram=""
report_RuningService=""
report_Crontab=""
report_Syslog=""
report_SNMP=""
report_NTP=""
report_JDK=""

function version(){
  echo ""
  echo ""
  echo "系统巡检脚本:Version $VERSION"
}

function getCpuStatus(){
  echo "############################ CPU检查 #############################"
  Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
  Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
  CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}')
  CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
  CPU_Arch=$(uname -m)
  echo "物理CPU个数:$Physical_CPUs"
  echo "逻辑CPU个数:$Virt_CPUs"
  echo "每CPU核心数:$CPU_Kernels"
  echo "CPU型号:$CPU_Type"
  echo "CPU架构:$CPU_Arch"
  report_CPUs=$Virt_CPUs
  report_CPUType=$CPU_Type
  report_Arch=$CPU_Arch
}

function getMemStatus(){
  echo "############################ 内存检查 ############################"
  if [[ $centosVersion < 7 ]]; then
    free -mo
  else
    free -h
  fi
  MemTotal=$(grep MemTotal /proc/meminfo| awk '{print $2}')
  MemFree=$(grep MemFree /proc/meminfo| awk '{print $2}')
  let MemUsed=MemTotal-MemFree
  MemPercent=$(awk "BEGIN {if($MemTotal==0){printf 100}else{printf \"%.2f\",$MemUsed*100/$MemTotal}}")
  report_MemTotal="$((MemTotal/1024))MB"
  report_MemFree="$((MemFree/1024))MB"
  report_MemUsedPercent="$MemPercent%"
}

function getDiskStatus(){
  echo "############################ 磁盘检查 ############################"
  df -hiP | sed 's/Mounted on/Mounted/' > /tmp/inode
  df -hTP | sed 's/Mounted on/Mounted/' > /tmp/disk
  join /tmp/disk /tmp/inode | awk '{print $1,$2,"|",$3,$4,$5,$6,"|",$8,$9,$10,$11,"|",$12}' | column -t
  diskdata=$(df -TP | sed '1d' | awk '$2!="tmpfs"{print}')
  disktotal=$(echo "$diskdata" | awk '{total+=$3}END{print total}')
  diskused=$(echo "$diskdata" | awk '{total+=$4}END{print total}')
  diskfree=$((disktotal-diskused))
  diskusedpercent=$(echo $disktotal $diskused | awk '{if($1==0){printf 100}else{printf "%.2f",$2*100/$1}}')
  inodedata=$(df -iTP | sed '1d' | awk '$2!="tmpfs"{print}')
  inodetotal=$(echo "$inodedata" | awk '{total+=$3}END{print total}')
  inodeused=$(echo "$inodedata" | awk '{total+=$4}END{print total}')
  inodefree=$((inodetotal-inodeused))
  inodeusedpercent=$(echo $inodetotal $inodeused | awk '{if($1==0){printf 100}else{printf "%.2f",$2*100/$1}}')
  report_DiskTotal=$((disktotal/1024/1024))GB
  report_DiskFree=$((diskfree/1024/1024))GB
  report_DiskUsedPercent="$diskusedpercent%"
  report_InodeTotal=$((inodetotal/1000))K
  report_InodeFree=$((inodefree/1000))K
  report_InodeUsedPercent="$inodeusedpercent%"
}

function getSystemStatus(){
  echo "############################ 系统检查 ############################"
  if [ -e /etc/sysconfig/i18n ]; then
    default_LANG="$(grep "LANG=" /etc/sysconfig/i18n | grep -v "^#" | awk -F '"' '{print $2}')"
  else
    default_LANG=$LANG
  fi
  export LANG="en_US.UTF-8"
  Release=$(cat /etc/redhat-release 2>/dev/null)
  Kernel=$(uname -r)
  OS=$(uname -o)
  Hostname=$(uname -n)
  SELinux=$(/usr/sbin/sestatus | grep "SELinux status: " | awk '{print $3}')
  LastReboot=$(who -b | awk '{print $3,$4}')
  uptime=$(uptime | sed 's/.*up \([^,]*\), .*/\1/')
  echo "系统:$OS"
  echo "发行版本:$Release"
  echo "内核:$Kernel"
  echo "主机名:$Hostname"
  echo "SELinux:$SELinux"
  echo "语言/编码:$default_LANG"
  echo "当前时间:$(date +'%F %T')"
  echo "最后启动:$LastReboot"
  echo "运行时间:$uptime"
  report_DateTime=$(date +"%F %T")
  report_Hostname="$Hostname"
  report_OSRelease="$Release"
  report_Kernel="$Kernel"
  report_Language="$default_LANG"
  report_LastReboot="$LastReboot"
  report_Uptime="$uptime"
  report_Selinux="$SELinux"
  export LANG="$default_LANG"
}

# Additional functions such as getServiceStatus() are defined later (omitted for brevity).

# Main execution (example)
version
getCpuStatus
getMemStatus
getDiskStatus
getSystemStatus
# ... call other functions and write results to $RESULTFILE
Linux system inspection illustration
Linux system inspection illustration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Linuxshell script
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.