端口变化,邮件告警(基于nmap端口扫描)
为了更好的把控公司外网端口变化,防止危险端口或者存在漏洞的应用端口开放至公网,我写了个shell脚本,通过nmap扫描,把变化的端口通过邮件每天发送至指定邮箱,实现外网端口变化检测,当然,也可用于内网。
完整代码 shell脚本
#!/bin/bash
###端口扫描,自动发送邮件
today=`date +%Y%m%d`
res_dir="result-scan"
current_dir="/usr/local/src/nmap-scan"
###邮箱地址
mail_user="xx@xxx.com"
if [ ! -d $current_dir ]; then
mkdir -p $current_dir
else
cd $current_dir
fi
if [ ! -d $res_dir ]; then
mkdir $res_dir
fi
if [ ! -f ip.txt ]; then
echo "Not Found IP List File,Exit!"
exit
fi
cat ip.txt | while read line
do
echo $line
nmap -v -Pn -sT -p1-65535 $line -oG $res_dir/$line-$today
cat $res_dir/$line-$today | sed 's/:/\n/g' | sed 's/,/\n/g' | grep / | grep open | sed 's/\
done
###文件对比
cd $res_dir
today_file="result-`date +%Y%m%d`-all.txt"
echo $today_file
if [ -f $today_file ]; then
rm -f $today_file
fi
cat log* >> $today_file
###删除log文件
rm -rf log*
yesterday_file="result-`date -d last-day +%Y%m%d`-all.txt"
echo $yesterday_file
if [ ! -f $yesterday_file ]; then
touch $yesterday_file
fi
diff_content=`diff -a $today_file $yesterday_file`
if [ $? -eq 0 ];then
echo "端口无变化,请忽略!" > same-$today
echo "No change"
cat "same-$today" | mail -s "【通知】无变化" $mail_user
else
diff -a $today_file $yesterday_file >> diff-$today
cat diff-$today | grep open | sed 's/</增加端口 /' | sed 's/>/减少端口/g' > diff-new-$today
cat diff-new-$today
if [ -f diff-$today ]; then
rm -f diff-$today
fi
cat diff-new-$today | mail -s "【警告】外网端口发生变化" $mail_user
fi
说明:
1.把需要扫描的IP地址写入ip.txt中
2.nmap安装
yum install nmap
3.邮件配置,以163为例
#创建证书,用于smtps,465端口
mkdir -p /root/.certs
echo -n | openssl s_client -connect smtp.163.com:465 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/.certs/163.crt
certutil -A -n "GeoTrust Global CA" -t "C,," -d ~/.certs -i ~/.certs/163.crt
certutil -A -n "GeoTrust SSL CA" -t "C,," -d ~/.certs -i ~/.certs/163.crt
certutil -L -d /root/.certs
#编辑/etc/mail.rc
set bsdcompat
set from=xxx@163.com
set smtp=smtps://smtp.163.com
set smtp-auth-user=xxx@163.com
set smtp-auth-password=xxx
set smtp-auth=login
set ssl-verify=ignore
set nss-config-dir=/root/.certs
4.定时任务,每天凌晨2点执行
crontab -e
0 2 * * * /bin/bash /usr/local/src/scan.sh >/tmp/log.out 2>&1