最新消息:

如何批量检测端口连通性、端口是否开放(二)

IT技术 ipcpu 5818浏览

如何批量检测端口连通性、端口是否开放(二)

本站之前有篇用nc来探测端口是否连通的文章,点我查看

端口探测无非也就是telnet、nc的命令,用法基本如下:

  1. [root@SY-68-2 ~]#echo "bye" | timeout 3 telnet www.baidu.com 81
  2. Trying 61.135.169.121...
  3. [root@SY-68-2 ~]#echo "bye" | timeout 3 telnet www.baidu.com 80
  4. Trying 61.135.169.125...
  5. Connected to www.baidu.com.
  6. Escape character is '^]'.
  7. Connection closed by foreign host.
  8. [root@SY-68-2 ~]#
  9. [root@SY-33-2 ~]# nc -z -w 5 www.baidu.com 80 && echo OK || echo Failed
  10. Connection to www.baidu.com 80 port [tcp/http] succeeded!
  11. OK
  12. [root@SY-68-2 ~]# nc -z -w 5 www.baidu.com 81 && echo OK || echo Failed
  13. Failed
  14. [root@SY-68-2 ~]#

今天我们来介绍一种新的bash自身包含的一种方式:
/dev/tcp/host/port 和 /dev/udp/host/port

用法也很简单:

  1. [root@SY-68-2 ~]# echo >/dev/tcp/www.baidu.com/80 && echo "port 80 is open" || echo "port 80 is closed"
  2. port 80 is open
  3. [root@SY-68-2 ~]#

但这种用法本身是不带超时时间设置的,幸好我们有timeout命令,组合起来便是:

  1. [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"
  2. port 80 is open
  3. [root@SY-68-2 ~]#
  4. [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"
  5. port 8080 is closed
  6. [root@SY-68-2 ~]#

就是如此,写一个for循环,便可以批量检测了。

样例文件如下:

  1. #cat ports
  2. 119.181.69.96 8080
  3. 220.181.111.188 80
  4. 119.181.20.18 8080
  5. 202.108.22.220 53

脚本和输出结果如下:

  1. cat ports | while read line
  2. do
  3. IP=`echo $line |awk '{print $1}'`
  4.   PORT=`echo $line |awk '{print $2}'`
  5. timeout 5 bash -c "echo >/dev/tcp/$IP/$PORT" > /dev/null 2>&1 && echo "$IP $PORT is open" || echo "$IP $PORT is closed"
  6. done
  7. # sh test.sh
  8. 119.181.69.96 8080 is closed
  9. 220.181.111.188 80 is open
  10. 119.181.20.18 8080 is closed
  11. 202.108.22.220 53 is open
来自为知笔记(Wiz)

转载请注明:IPCPU-网络之路 » 如何批量检测端口连通性、端口是否开放(二)