天天看點

Linux下批量檢測端口的連通性的幾種方式

目錄

  • ​​1.Linux下端口的幾種狀态​​
  • ​​2.timeout+bash批量檢測端口連通性​​
  • ​​3.使用nc檢測端口連通性​​
  • ​​參考連結​​

1.Linux下端口的幾種狀态

通常Linux下端口存在以下狀态
  1. 端口開放且已經有服務占用該端口

    ​​

    ​open​

  2. 端口開放但沒有服務占用該端口

    ​​

    ​Connection refused​

  3. 端口被禁用(如:防火牆限制)

    ​​

    ​Connection timed out​

2.timeout+bash批量檢測端口連通性

背景需求:162伺服器需要對197從6000到6010端口進行連通性檢測

通過檢視197伺服器上端口得知

  • 目前6001-6010端均被redis-server占用,
  • 6000端口目前無服務占用,
  • 人工執行iptables對6001和6005,6008端口做iptables限制,模拟端口被禁用
Linux下批量檢測端口的連通性的幾種方式
iptables -A INPUT -p tcp --dport 6001 -j DROP
iptables -A INPUT -p tcp --dport 6005 -j DROP
iptables -A INPUT -p tcp --dport 6008 -j DROP      
Linux下批量檢測端口的連通性的幾種方式
編寫小腳本對端口進行來連通性檢測
#!/bin/bash

PORT_LIST="6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010"
REMOTE_HOST=10.186.61.197
TIMEOUT_SEC=5

for PORT in $PORT_LIST
do
    timeout $TIMEOUT_SEC bash -c "</dev/tcp/$REMOTE_HOST/$PORT" &>/dev/null; res=$?
    if [[ $res -eq 0 ]]
    then
        echo "$PORT OPEN"
    elif [[ $res -eq 1 ]]
    then
        echo "$PORT OPEN BUT NOT LISTEN"
    elif [[ $res -eq 124 ]]
    then
        echo "$PORT NOT OPEN"
    else
        echo "$PORT UNKONWN ERROR"
    fi
done      

檢測結果示例

  • ​OPEN BUT NOT LISTEN​

  • 端口開放但沒有服務占用該端口
  • ​OPEN​

  • 端口開放且已經有服務占用該端口
  • ​NOT OPEN​

  • 端口被禁用(如:防火牆限制)
Linux下批量檢測端口的連通性的幾種方式

3.使用nc檢測端口連通性

[root@10-186-61-162 ~]# nc -w 5  10.186.61.197 6000 </dev/null; echo $?
Ncat: Connection refused.
1
[root@10-186-61-162 ~]# nc -w 5  10.186.61.197 6001 </dev/null; echo $?
Ncat: Connection timed out.
1
[root@10-186-61-162 ~]# nc -w 5  10.186.61.197 6002 </dev/null; echo $?
0      

繼續閱讀