适用场景
入侵检测脚本是服务器安全应急响应中的核心工具。本文以 Linux 入侵检测脚本 为主线,讲解如何编写一套可自动运行的检测程序,用于发现新增用户、异常登录、恶意进程与篡改文件等入侵痕迹,适合安全运维人员、服务器管理员在等保测评与日常巡检场景中直接落地。
前置条件
- 操作系统:Linux(内核 3.10+),具备 root 权限执行审计命令
- 运行环境:Python 3.6+ 与 bash 4+
- 建议部署在独立审计服务器,或与业务主机分离存放告警日志
原理说明
入侵检测脚本的核心思路是“差异对比 + 行为特征”,通过四个维度发现入侵痕迹:
- 文件完整性:对比敏感文件(/etc/passwd、/etc/shadow、/etc/ssh/sshd_config 等)的修改时间与哈希,发现被篡改或新增的后门文件
- 账号审计:比对用户快照,发现攻击者新建的隐藏账号(尤其是 UID=0 的高危账号)
- 登录与进程监控:统计失败登录次数、检查异常监听端口
- 定时任务与启动项:检查 crontab、systemd 服务中的持久化后门
脚本将检测结果写入日志,异常项通过 Webhook 实时告警,实现“先发现、后处置”的闭环。
操作步骤
第一步:创建脚本目录与敏感文件清单
mkdir -p /opt/idetect/{bin,data,log}
cd /opt/idetect
cat > /opt/idetect/data/file_list.txt <<'LIST_END'
/etc/passwd
/etc/shadow
/etc/group
/etc/sudoers
/etc/ssh/sshd_config
/etc/rc.local
/etc/crontab
LIST_END
第二步:编写基线快照脚本
#!/bin/bash
# /opt/idetect/bin/snapshot.sh - 生成用户与监听端口基线
getent passwd | cut -d: -f1,3,6 > /opt/idetect/data/users.baseline
ss -tlnp | md5sum > /opt/idetect/data/ports.md5
echo "[$(date '+%F %T')] snapshot updated" >> /opt/idetect/log/snapshot.log
第三步:编写核心检测脚本 detect.py
#!/usr/bin/env python3
# /opt/idetect/bin/detect.py - Linux 入侵检测脚本(核心)
import hashlib, os, subprocess, sys, datetime
BASE = '/opt/idetect'
ALERT = []
def run(cmd):
return subprocess.run(cmd, shell=True, capture_output=True,
text=True).stdout.strip()
def check_file_integrity():
"""对比敏感文件哈希,发现篡改与新增后门"""
flist = f'{BASE}/data/file_list.txt'
baseline = set(open(f'{BASE}/data/files.baseline').read().splitlines())
for path in [l.strip() for l in open(flist) if l.strip()]:
if not os.path.exists(path):
ALERT.append(f'[文件缺失] {path}')
continue
h = hashlib.sha256(open(path, 'rb').read()).hexdigest()
if f'{h} {path}' not in baseline:
ALERT.append(f'[文件变更] {path} (sha256: {h[:16]})')
def check_new_users():
"""审计 UID=0 账号与新增用户"""
for line in run('getent passwd').splitlines():
name, _, uid = line.split(':')[:3]
if uid == '0' and name != 'root':
ALERT.append(f'[高危账号] UID=0 非 root: {name}')
def check_login_failures():
"""统计 24 小时内登录失败次数(爆破迹象)"""
log = '/var/log/auth.log'
if os.path.exists('/var/log/secure'):
log = '/var/log/secure'
day = datetime.datetime.now().strftime('%b %e')
fails = run(f"grep 'Failed password' {log} | grep -c '{day}'")
if fails.isdigit() and int(fails) > 50:
ALERT.append(f'[爆破迹象] 24h 登录失败 {fails} 次')
def check_listening_ports():
"""发现异常监听端口(与基线比对)"""
cur = run('ss -tlnp | md5sum')
if cur != open(f'{BASE}/data/ports.md5').read().strip():
ALERT.append('[端口变化] 监听端口与基线不一致,请人工核查')
def main():
check_file_integrity(); check_new_users()
check_login_failures(); check_listening_ports()
if ALERT:
msg = '
'.join(ALERT)
print(f'[ALERT {datetime.datetime.now():%F %T}]
{msg}')
# 告警:解除注释并替换地址即可接入 Webhook
# run(f'curl -s -X POST -d "alert={msg}" http://alert.example.com/hook')
else:
print('[OK] 未发现异常')
if __name__ == '__main__':
main()
第四步:初始化基线并设置定时任务
chmod +x /opt/idetect/bin/snapshot.sh /opt/idetect/bin/detect.py
/opt/idetect/bin/snapshot.sh
# 生成文件哈希基线(按清单顺序)
while read f; do sha256sum "$f"; done < /opt/idetect/data/file_list.txt > /opt/idetect/data/files.baseline
# 每天 3:00 更新快照,6:10 执行检测
(crontab -l 2>/dev/null; echo '0 3 * * * /opt/idetect/bin/snapshot.sh') | crontab -
(crontab -l 2>/dev/null; echo '10 6 * * * /usr/bin/python3 /opt/idetect/bin/detect.py >> /opt/idetect/log/detect.log 2>&1') | crontab -
配置验证
# 1. 正常状态运行
python3 /opt/idetect/bin/detect.py
# 期望输出: [OK] 未发现异常
# 2. 制造一条“入侵痕迹”验证检出能力
useradd -o -u 0 backdoor_test
python3 /opt/idetect/bin/detect.py
# 期望输出: [ALERT ...] [高危账号] UID=0 非 root: backdoor_test
userdel backdoor_test
验证输出应包含 [高危账号] UID=0 非 root: backdoor_test,说明脚本能有效发现攻击者常用的“克隆 root 账号”手法;同时 crontab -l 可查看到两条定时任务已生效。
常见问题
Q1:检测到大量误报怎么办?
首次运行后应将合法变更写入基线:重新执行文件哈希生成命令覆盖 files.baseline,并将合法端口快照更新到 ports.md5。建议对告警分级——文件完整性校验每天一次,登录失败审计保持高频,减少噪声。
Q2:脚本被攻击者篡改或停掉怎么办?
将 /opt/idetect 目录权限收紧为 root-only(chmod -R 700 /opt/idetect),基线文件定期异地备份;更稳妥的做法是引入 文件完整性工具 AIDE 对脚本自身做二次校验,并把检测结果通过 syslog 转发到独立日志服务器,防止攻击者清理现场。
Q3:如何实现实时告警而不是每天一次?
把 detect.py 的调用频率提高到每 5 分钟一次,并在告警分支接入企业微信/钉钉 Webhook:将示例中注释的 curl 行解除并替换为机器人地址即可。
总结
本文提供了一套可直接部署的 Linux 入侵检测脚本:通过文件哈希基线、UID=0 账号审计、登录失败统计与端口基线比对,覆盖入侵检测最常用的四个维度。配合 crontab 定时执行与 Webhook 告警,可实现无人值守的安全巡检。生产环境建议在此基础上补充 ELK 日志集中采集与 AIDE 完整性校验,形成纵深防御体系。