timeout 1 bash -c 'cat < /dev/null > /dev/tcp/google.com/80'
$ echo $?
0
看返回结果: 结果是0就是通 结果是其他数字就是不通
nmap-ncat测试尚未使用的本地端口
availabletobindon() {
port="$1"
nc -w 2 -i 1 localhost "$port" 2>&1 | grep -v -q 'Idle timeout expired'
return "$?"
}
在某些情况下,例如curl,telnet,nc o nmap等工具不可用,您仍然有机会使用wget
if [[ $(wget -q -t 1 --spider --dns-timeout 3 --connect-timeout 10 host:port; echo $?) -eq 0 ]]; then echo "OK"; else echo "FAIL"; fi
使用bash检查端口
例
$ ./test_port_bash.sh 192.168.7.7 22
端口22是开放的
脚本
HOST=$1
PORT=$2
exec 3> /dev/tcp/${HOST}/${PORT}
if [ $? -eq 0 ];then echo "the port $2 is open";else echo "the port $2 is closed";fi
在Bash中,使用伪设备文件进行TCP / UDP连接很简单。
脚本
#!/usr/bin/env bash
SERVER=example.com
PORT=80
</dev/tcp/$SERVER/$PORT
if [ "$?" -ne 0 ]; then
echo "Connection to $SERVER on port $PORT failed"
exit 1
else
echo "Connection to $SERVER on port $PORT succeeded"
exit 0
fi
测试
$ ./test.sh
Connection to example.com on port 80 succeeded
这是单行(Bash语法):
</dev/tcp/localhost/11211 && echo Port open. || echo Port closed.
参考连接:
https://stackoverflow.com/questions/4922943/test-if-remote-tcp-port-is-open-from-a-shell-script