端口探测无非也就是telnet、nc的命令,用法基本如下:
[root@SY-68-2 ~]#echo "bye" | timeout 3 telnet www.baidu.com 81
Trying 61.135.169.121...
[root@SY-68-2 ~]#echo "bye" | timeout 3 telnet www.baidu.com 80
Trying 61.135.169.125...
Connected to www.baidu.com.
Escape character is '^]'.
Connection closed by foreign host.
[root@SY-68-2 ~]#
[root@SY-33-2 ~]# nc -z -w 5 www.baidu.com 80 && echo OK || echo Failed
Connection to www.baidu.com 80 port [tcp/http] succeeded!
OK
[root@SY-68-2 ~]# nc -z -w 5 www.baidu.com 81 && echo OK || echo Failed
Failed
[root@SY-68-2 ~]#
bash自身包含的一种方式:
/dev/tcp/host/port 和 /dev/udp/host/port
用法也很简单:
[root@SY-68-2 ~]# echo >/dev/tcp/www.baidu.com/80 && echo "port 80 is open" || echo "port 80 is closed"
port 80 is open
[root@SY-68-2 ~]#
但这种用法本身是不带超时时间设置的,幸好我们有timeout命令,组合起来便是:
[root@SY-68-2 ~]#timeout 5 bash -c "echo >/dev/tcp/www.baidu.com/80" > /dev/null 2>&1 && echo "port 80 is open" || echo "port 80 is closed"
port 80 is open
[root@SY-68-2 ~]#
[root@SY-68-2 ~]#timeout 5 bash -c "echo >/dev/tcp/www.baidu.com/8080" > /dev/null 2>&1 && echo "port 8080 is open" || echo "port 8080 is closed"
port 8080 is closed
[root@SY-68-2 ~]#
就是如此,写一个for循环,便可以批量检测了。
样例文件如下:
#cat ports
119.181.69.96 8080
220.181.111.188 80
119.181.20.18 8080
202.108.22.220 53
脚本和输出结果如下:
cat ports | while read line
do
IP=`echo $line |awk '{print $1}'`
PORT=`echo $line |awk '{print $2}'`
timeout 5 bash -c "echo >/dev/tcp/$IP/$PORT" > /dev/null 2>&1 && echo "$IP $PORT is open" || echo "$IP $PORT is closed"
done
# sh test.sh
119.181.69.96 8080 is closed
220.181.111.188 80 is open
119.181.20.18 8080 is closed
202.108.22.220 53 is open