1、任务场景
随着企业信息化和云计算技术的快速发展,Linux 系统已成为核心服务器平台。特别是 CentOS Stream 9,作为一个社区驱动的企业级操作系统,其稳定性和安全性要求较高。系统巡检和健康检查已经成为系统管理的重要组成部分。
在日常运维中,管理员往往需要定期执行一系列检查操作,例如:
- 检查 CPU、内存、磁盘的使用情况。
- 检查系统负载、活动进程和日志信息。
- 确保防火墙、SELinux 等安全设置的有效性。
目前,手动执行这些检查任务耗时且容易出错,因此需要一个自动化脚本来定期执行这些任务,并将检查结果保存为日志,以供运维人员查看和分析。
问题有两个方面:① 比较长(抵触)② 大家对基础命令不够熟悉
2、任务拆解
2.1 日志文件路径定义 => LOGFILE=/var/log/centos_stream_9_health_check.log
2.2 开始检查写入日志 => echo "检查结果" >> $LOGFILE
2.3 系统负载检查 => uptime
2.4 CPU 使用情况检查 => top(需要自己处理,获取cpu使用率)
2.5 内存使用情况检查 => free -h
2.6 磁盘使用情况检查 => df -h
2.7 活动进程检查 => ps aux
2.8 最近的系统日志检查 => journalctl -n 10
2.9 系统更新检查 => dnf check-update
2.10 SELinux 状态检查 => sestatus
2.11 防火墙状态检查 => firewall-cmd --state
2.12 当前挂载的磁盘检查 => lsblk
2.13 Cron 任务列表检查 => crontab -l
2.14 系统基本信息检查 => hostname && uname -r
3、任务实施
#!/bin/bash
# 定义日志文件路径
LOG_FILE="/var/log/centos_stream_9_health_check.log"
current_time=$(date +"%Y-%m-%d %H:%M:%S")
# 写入日志函数
echo "$current_time - Starting daily health check..." >> $LOG_FILE
# 系统负载检查
echo "$current_time - System Load: $(uptime)" >> $LOG_FILE
# CPU 使用情况检查
echo "$current_time - CPU Usage: $(top -bn1 | grep 'Cpu(s)' | cut -d',' -f4 | cut -d' ' -f2 | awk '{print 100 - $1}')" >> $LOG_FILE
# 内存使用情况检查
echo "$current_time - Memory Usage: $(free -h)" >> $LOG_FILE
# 磁盘使用情况检查
echo "$current_time - Disk Usage: $(df -h)" >> $LOG_FILE
# 活动进程检查
echo "$current_time - Top 10 CPU consuming processes: $(ps aux --sort=-%cpu | head -n 10)" >> $LOG_FILE
# 网络连接状态检查
echo "$current_time - Network Connections: $(ss -tunlp)" >> $LOG_FILE
# 最近的系统日志检查
echo "$current_time - Recent System Logs: $(journalctl -n 10)" >> $LOG_FILE
# 系统更新检查
echo "$current_time - System Updates: $(dnf check-update)" >> $LOG_FILE
# SELinux 状态检查
echo "$current_time - SELinux Status: $(sestatus)" >> $LOG_FILE
# 防火墙状态检查
echo "$current_time - Firewall Status: $(firewall-cmd --state)" >> $LOG_FILE
# 当前挂载的磁盘检查
echo "$current_time - Mounted Disks: $(lsblk)" >> $LOG_FILE
# Cron 任务列表检查
echo "$current_time - Cron Jobs: $(crontab -l)" >> $LOG_FILE
# 系统基本信息检查
echo "$current_time - System Info: $(hostname && uname -a)" >> $LOG_FILE
# 写入日志结束
echo "$current_time - Health check completed." >> $LOG_FILE
exit 0
备注:ps aux --sort=-%cpu,-%cpu,代表按照%cpu这列降序排列,-代表降序的意思