nmap端口扫描+邮件告警

Nmap是一款网络扫描和主机检测的非常有用的工具。本次通过nmap进行主机端口扫描,并通过邮件进行告警。

#!/bin/bash
###wsl
mail_user="……@qq.com"
today=$(date +%Y%m%d)
yesterday=$(date -d last-day +%Y%m%d)
before=$(date -d "2 days ago" +%Y%m%d)
nmap_ip="192.168.37"
nmap_record="/nmap-record"
###邮件发送
send_mail () {
cd $nmap_record
cat same-$today | mail -s "same" $mail_user
}
send_mail_change () {
cd $nmap_record
cat diff-$today | mail -s "increase/decrease" $mail_user
}
###端口扫描
NMAP_PORT_CHECK(){
if [ ! -f $nmap_record ];then
mkdir $nmap_record
fi
cd $nmap_record
for i in {10..12};do
ping -c 1 $nmap_ip.$i > /dev/null
if [ $? -eq 0 ];then
testfile="$i--$today"
nmap_port=`nmap "$nmap_ip"."$i" | grep ^[1-9] | awk -F/ '{print $1}' > $testfile`
else
echo "$i not alive"
fi
done
}
###文件对比
NMAP_PORT_DIFF(){
cd $nmap_record
for i in {10..12};do
todayfile="$i--$today"
yesterdayfile="$i--$yesterday"
if [ -f $todayfile ];then
diff -a $todayfile $yesterdayfile
if [ $? -eq 0 ];then
echo "$nmap_ip"."$i" >> same-$today
SAME=`nmap "$nmap_ip"."$i" | grep ^[1-9] | awk -F/ '{print $1} >> same-$today'`
else
echo "$nmap_ip"."$i" >> diff-$today
DIFF=`diff -a $todayfile $yesterdayfile >> diff-$today`
fi
fi
done
}
###以前对比文件删除
DELETE(){
cd $nmap_record
if [ -f *-$before ];then
rm -rf *-$before
fi
}
###启动脚本
start(){
NMAP_PORT_CHECK
NMAP_PORT_DIFF
send_mail
send_mail_change
DELETE
}
$1

通过建立计划任务在服务器的某个时间点进行端口扫描,并对比开放的端口是否有所不同。这个脚本中是有不同和相同都发邮件,如果想只发不同的,只需把【send_mail】这个函数的内容注释掉就行。

以下是脚本执行后,邮箱所收内容的截图:

主机端口比对不同:

nmap端口扫描+邮件告警_第1张图片

主机端口比对相同:

nmap端口扫描+邮件告警_第2张图片

 
 

你可能感兴趣的:(脚本编写)