我正在运行以下命令来测试端口连接
curl -v telnet://target ip address:desired port number
当服务器连接成功时,我看到的输出如下。
# curl -v telnet://127.0.0.1:22
* About to connect() to 127.0.0.1 port 22 (#0)
* Trying 127.0.0.1... connected
* Connected to 127.0.0.1 (127.0.0.1) port 22 (#0)
当服务器没有成功连接时,我看到的输出如下图所示
# curl -v telnet://127.0.0.1:22
* About to connect() to 127.0.0.1 port 22 (#0)
* Trying 127.0.0.1...
现在,对于一个给定的服务器列表,我试图用bash脚本来自动化它。
for element in "${array[@]}"; do
timeout 2s curl -v telnet://"$element":22 >/dev/null 2>&1
if [ $? -eq 0 ]; then
echo "'$element' connected" && break
else
echo "Connection with $element failed."
fi
done
数组有一些值。
abc001
abc002
abc003
我总是从内部得到输出 else
声明
Connection with abc001 failed.
Connection with abc002 failed.
Connection with abc003 failed.
我想这是因为返回代码总是为 124
错误代码是 124
成败参半
我如何修改我的脚本才能正常工作?
你可以 grep
输出一些表示成功的字符串。 例如,,
if timeout 2s curl -v telnet://"$element":22 2>&1 | grep "Connected to"; then
...
else
...
fi
curl
有一个可选的参数 --connect-timeout <seconds>
. 我的建议是修改你的 curl
命令改为类似。
for element in "${array[@]}"; do
curl -v --connect-timeout 2 telnet://"${element}":22
if [[ $? -eq 0 ]]; then
echo "'${element}' connected"
else
echo "Connection with ${element} failed."
fi
done
一个很好的参考是 curl man page.