脚本检查IP地址和MAC是否对应
需求
需要把一批次的IP地址和MAC地址进行绑定,如果该IP地址没有和MAC对应则输出
脚本如下
# cat check_arp.sh
#!/bin/bash
# 检查ip地址和mac是否对应
IpList=()
MacList=("<incomplete>" "<incomplete>" "<incomplete>" "74:56:3c:63:c4:c7" "<incomplete>" "40:b0:34:3e:c7:1f" "04:7c:16:c0:ba:48" "<incomplete>" "<incomplete>" "<incomplete>" "<incomplete>" "<incomplete>" "<incomplete>" "<incomplete>" "<incomplete>" "f8:75:a4:35:0a:e4" "08:26:ae:3f:75:e2" "c8:5b:76:3e:ee:c9" "08:26:ae:3f:75:b0" "74:d4:dd:1e:6c:e6")
Len=${#MacList[@]}
# echo "length is $Len"
CheckMacList=()
# 生成ip地址列表从192.168.8.91至192.168.8.110
StartNum=91
EndNum=110
for((i=$StartNum;i<=$EndNum;i++))
do
IpList+=("192.168.8.${i}")
done
# ping ip地址如果能ping通则会存储至本地arp列表
for i in ${IpList[*]}
do
ping $i -c 1
done
# 循环ip列表把arp信息存重定向至以日期时间为名的文件
Time=`date +%Y%m%d%H%M`
LOG=/var/log/${Time}checkarp.list
for i in ${IpList[*]}
do
arp -a $i >> ${LOG}
done
# 通过读取生成文件获取到对应mac然后和原始的MacList表进行对比
for i in `awk '{print $4}' ${LOG}`
do
CheckMacList+=("$i")
done
n=0
for((i=0;i<$Len;i++))
do
if [ "${CheckMacList[$i]}" != "<incomplete>" -a "${CheckMacList[$i]}" != "${MacList[$i]}" ]
then
echo "${Time} Someone has set an incorrect IP address ${IpList[$i]}" >> /var/log/cherk_arp.log
n=n+1
fi
done
if [ ${n} -eq 0 ]
then
echo "${Time} No problem" >> /var/log/cherk_arp.log
fi
解释
- 两个shell列表一个是对应IP地址列表,一个是对应的MAC地址列表
- 循环获取IP列表的MAC地址,获取MAC地址需要先ping一下否则arp表可能没有存储该MAC
- 如果该IP地址有但是没有和MAC表对应则代表有问题了则输出日志
把该脚本定时任务运行即可,有必要则添加告警如邮件告警