在日常的生产环境中,可能会遇到需要批量检查内网目前在线的主机IP地址有哪些,还可能需要检查这些在线的主机哪些端口是开放状态,因此依靠手工来检查是可以实现,但比较费时费力,所以需要结合shell脚本来实现批量检查的功能,那么今天就来做个小小的实验。
PING 172.16.1.1 (172.16.1.1) 56(84) bytes of data.^C
rtt min/avg/max/mdev = 0.525/1.053/3.436/0.884 ms
PING 172.16.1.1 (172.16.1.1) 56(84) bytes of data.--- 172.16.1.1 ping statistics ---
[root@centos6 scripts]#ping -W 2 -c 2 172.16.1.100
--- 172.16.1.100 ping statistics ---
1
既然有实现的方法了,那么接下来就开始开发脚本了
. /etc/init.d/functions
#定义命令变量
for n in $IP
$CMD $IP$n >/dev/null 2>&1
#如果返回值为0就表明在线
else
#不在线就打印此信息
执行下脚本看看结果如何
172.16.1.3 is online [ OK ]
此时肯定有小伙伴问了,你这个脚本测试的只有三个IP,如果内网整个网段IP都手工写上去,岂不是更费时费力,因此,如果是整个网段,那么定义IP变量时可以定义成这样IP="172.16.1." ,因为前三位是相同的,写for 循环时可以修改成如下
$CMD $IP$n(将两段数字拼接成IP地地址)
Starting Nmap 5.51 ( http://nmap.org ) at 2016-12-03 21:09 CST
MAC Address: 04:BD:70:FB:A9:B7 (Unknown)
Starting Nmap 5.51 ( http://nmap.org ) at 2016-12-03 21:09 CST
[root@centos6 scripts]#nmap -sS 172.16.1.1|grep "Nmap scan report for"nmap -sS 172.16.1.1|grep "Nmap scan report for"|awk '{print $5}'
Starting Nmap 5.51 ( http://nmap.org ) at 2016-12-03 20:56 CSTNot shown: 994 closed ports
22/tcp filtered ssh
179/tcp filtered bgp
Nmap done: 1 IP address (1 host up) scanned in 8.74 seconds
[root@centos6 scripts]# nmap -sS 172.16.1.1|grep "open"80/tcp open http
21/tcp
443/tcp
4、编写脚本并测试效果
. /etc/init.d/functions
#定义第一个命令变量
TCMD="nmap -sS"
#定义获取在线IP的变量
do
UPPORT=`$TCMD $ip|grep "open"|awk '{print $1}'`
#二层循环检查端口
#将上面在线IP开放的端口信息打印输出
注:UPPORT=`$TCMD $ip|grep "open"|awk '{print $1}'` 定义这个变量时,取的IP地址一定要是上一个循环取出的IP地址,否则会有问题
172.16.1.1 is on line [ OK ]
172.16.1.1 80/tcp is open [ OK ]
172.16.1.2 23/tcp is open [ OK ]
Connected to 172.16.1.1.
telnet> quit
Trying 172.16.1.1...
220 FTP service ready.
Connection closed.
Connected to 172.16.1.2.
telnet> quit
脚本写的可能也不太完美,需要进行改进,欢迎各位大牛多指导,感谢!!!