CentOS 7 日志管理
一、实验目的
- 掌握 CentOS 7 系统日志的存储位置与查看方法
- 学会配置日志轮转策略
- 掌握日志分析工具(grep/awk/sed)的使用
- 实现日志集中管理(rsyslog)
- 了解日志监控与报警机制
二、实验环境
- 操作系统:CentOS 7
- 硬件要求:内存 1GB 以上
- 权限要求:需以 root 用户登录系统
三、实验准备
-
确保实验环境中有运行中的服务(如 httpd)
-
安装实验所需工具:
yum install -y httpd logwatch
四、实验步骤
(一)日志文件基础操作
1. 查看系统日志
# 查看系统核心日志
cat /var/log/messages
# 查看认证日志(SSH 登录记录)
cat /var/log/secure
# 查看服务日志(如 httpd)
tail -f /var/log/httpd/access_log
2. 实时监控日志
# 实时查看认证日志变化
tail -f /var/log/secure
3. 日志文件清理(谨慎操作)
# 清空日志文件
> /var/log/httpd/access_log
(二)日志轮转配置
1. 查看当前轮转策略
# 查看系统默认日志轮转配置
ls -l /etc/logrotate.d/
2. 自定义日志轮转策略
# 创建新的轮转配置文件
vi /etc/logrotate.d/httpd_log
配置内容:
/var/log/httpd/*.log {
daily
rotate 7
missingok
compress
delaycompress
notifempty
create 0644 root root
}
参数说明:
daily
:按天轮转rotate 7
:保留 7 份旧日志compress
:压缩旧日志create
:创建新日志文件并设置权限
3. 立即执行日志轮转
logrotate -f /etc/logrotate.conf
(三)日志分析工具
1. 使用 grep 过滤日志
# 查找 SSH 登录失败记录
grep "Failed password" /var/log/secure
# 查找特定时间段的日志
grep "Jan 10" /var/log/messages
2. 使用 awk 统计数据
# 统计 Apache 访问日志中各 IP 的请求次数
awk '{print $1}' /var/log/httpd/access_log | sort | uniq -c
3. 使用 sed 替换内容
# 将日志中的敏感信息替换为 ***
sed -i 's/192.168.1.[0-9]*/***.***.***.***.*/g' /var/log/httpd/access_log
(四)日志集中管理(rsyslog)
1. 配置日志服务器
# 编辑 rsyslog 配置文件
vi /etc/rsyslog.conf
添加内容:
# 接收 UDP 日志
$ModLoad imudp
$UDPServerRun 514
# 接收 TCP 日志
$ModLoad imtcp
$InputTCPServerRun 514
# 重启 rsyslog 服务
systemctl restart rsyslog
2. 配置客户端发送日志
# 编辑客户端 rsyslog 配置
vi /etc/rsyslog.conf
添加内容:
*.* @192.168.1.100:514
# 重启客户端 rsyslog 服务
systemctl restart rsyslog
3. 验证日志接收
# 在日志服务器查看接收的日志
tail -f /var/log/messages
(五)日志监控与报警
1. 使用 Logwatch 生成报告
# 安装 Logwatch
yum install -y logwatch
# 生成详细日志报告
/usr/sbin/logwatch --detail high
# 设置定时任务每天发送报告
crontab -e
添加内容:
0 6 * * * /usr/sbin/logwatch --mailto admin@example.com
2. 使用 Monit 监控日志
# 安装 Monit
yum install -y monit
# 编辑监控配置
vi /etc/monitrc
添加内容:
check file httpd_log with path /var/log/httpd/access_log
if changed timestamp then alert
# 重启 Monit 服务
systemctl restart monit
五、实验总结
通过本实验,你将掌握:
- 系统日志的查看与管理方法
- 日志轮转策略的配置与验证
- 日志分析工具的实际应用
- 日志集中管理的实现步骤
- 日志监控与报警机制的搭建
六、注意事项
- 清理日志前务必确认文件内容
- 配置日志轮转时需合理设置保留天数
- 日志集中管理需确保网络连通性
- 敏感日志数据需进行脱敏处理
- 报警机制需设置合理的触发条件
提示:实验中建议使用虚拟机环境,避免对生产系统日志造成干扰。