shell扫描局域网脚本
脚本目的是扫描局域网内设备,输出在线设备(可ping通)列表,再通过nbtscan扫描在线设备的真实IP和MAC地址
脚本使用方式为将脚本文件建立在/etc/cron.hourly/下,通过crontab实现每小时自动运行
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
#!/bin/bash network=192.168.1 #局域网内ip地址网络ID dir=/var/log/flush-ip nowlog=`date +%F-%H`.log lastloghour=$[ 10#`date +%H`-1 ] if (( "$lastloghour"<0 ));then $lastloghour=23 lastlog=`date +%Y-%m`-$[`date +%d-1`]-`printf "%02d" $lastloghour`.log else lastlog=`date +%F`-`printf "%02d" $lastloghour`.log fi #Delete more than 24 hours of files find ${dir}/ -name *.log -mtime +0 -print -exec rm -f {} \; >/dev/null rm -f $dir/$nowlog &>/dev/null for host in $(seq 2 254) do ping -c 1 -w 1 $network.$host &>/dev/null && result=0 || result=1 if [ "$result" == 0 ];then echo $network.$host &>>$dir/$nowlog fi done diff $dir/$nowlog $dir/$lastlog >$dir/diff.log 2>/dev/null && diff=0||diff=1 if [ "$diff" == 1 ];then #cat -n $dir/diff.log rm -f $dir/addlist.log $dir/dellist.log >/dev/null touch $dir/addlist.log $dir/dellist.log >/dev/null row=`cat $dir/diff.log|wc -l` if [ "$row" == 0 ];then cp $dir/$nowlog $dir/$addlist.log >/dev/null else for num in $(seq 1 $row) do var=`sed -n ${num}p $dir/diff.log` if [ "${var:0:1}" == "<" ];then echo ${var:2} >>$dir/addlist.log fi if [ "${var:0:1}" == ">" ];then echo ${var:2} >>$dir/dellist.log fi done fi cat -n $dir/$nowlog echo "ADD" cat -n $dir/addlist.log nbtscan -f $dir/addlist.log | tail -n +4 echo "LEAVE" cat -n $dir/dellist.log fi |