1.Linux下端口的幾種狀態
通常Linux下端口存在以下狀態
- 端口開放且已經有服務占用該端口
open
- 端口開放但沒有服務占用該端口
Connection refused
- 端口被禁用(如:防火牆限制)
Connection timed out
2.timeout+bash批量檢測端口連通性
背景需求:162服務器需要對197從6000到6010端口進行連通性檢測
通過查看197服務器上端口得知
- 當前6001-6010端均被redis-server占用,
- 6000端口當前無服務占用,
- 人工執行iptables對6001和6005,6008端口做iptables限制,模擬端口被禁用
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
編寫小腳本對端口進行來連通性檢測
#!/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
- 端口被禁用(如:防火牆限制)
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