用shell对指定站点进行简单的实时入侵预警

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/bin/bash
# author by klion
# 2017.12.25
# Real-time monitoring of Web Directory script
web_dir="/usr/local/nginx/html/bwapp/bWAPP/"
oldnum=`wc -l web_history_db.log | awk -F " " '{print $1}'`
newnum=`find $web_dir -type f | wc -l`
md5num=`md5sum -c web_history_db.log | grep -i FAILED | wc -l`
# 先对指定的站点目录创建指纹库
[ ! -f web_history_db.log ] && {
find $web_dir -type f | xargs md5sum > ./web_history_db.log
}
# 和新文件对比指纹,如果发现不对,就马上发信通知,并带上被改动的文件路径一起
[ $md5num -ne 0 ] && {
md5sum -c web_history_db.log | grep -i "FAILED" | awk -F ":" '{print $1}' > web_mod_`date +%Y-%m-%d-%H-%M-%S`.web.log
log_file=`ls -l *.web.log | head -n 1 | awk -F " " '{print $9}'`
mail -s "Your website may be hacked, Please check it as soon as possible" klion@protonmail.com < $log_file;sleep 5
rm -fr $log_file
}
# 对比文件个数,发现不对,同样是立马发信,因为有可能要同时监控很多个站点目录,所以就顺便把具体的站点路径也带上了
[ $oldnum -ne $newnum ] && {
echo "website directory is $web_dir" | mail -s "web directory have new file created " klion@protonmail.com ;sleep 5
}



后话:
    小脚本实现的功能非常简单,只要所指定的站点目录下有任何的文件属性变化,包括,新文件或目录的增删改查以及对现有文件的篡改,就会自动向管理员发信报警,此处只是为了快速实现效果,所以就直接用shell搞了,实际要想用,也可自行用python写的更完善一些 ^_^