【问题标题】:How to correctly use telnet in a bash script?如何在 bash 脚本中正确使用 telnet?
【发布时间】:2020-08-30 12:56:34
【问题描述】:

我正在运行以下命令来测试端口连接

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

如何修改我的脚本以使其正常工作?

【问题讨论】:

  • 即使连接成功返回码也是124?
  • 是的,成功和失败都是 124
  • 这……很奇怪。也许你可以grep 输出一些指示成功的字符串。
  • 我可以 grep 获取Connected ,但您能提供更新后的脚本吗?提前致谢
  • @mealhour :如果您想找出连接被拒绝的原因,为什么要从 telnet 命令中丢弃 stderr?此外,在 2 秒超时窗口内,与 abc123 的命令行连接是否有效?

标签: linux bash curl telnet rhel


【解决方案1】:

您可以grep 输出一些指示成功的字符串。例如,

if timeout 2s curl -v telnet://"$element":22 2>&1 | grep "Connected to"; then
    ...
else
    ...
fi

【讨论】:

  • 它仍在执行else语句Connection with abc001 failed. Connection with abc002 failed. Connection with abc003 failed.
  • 我应该在timeout前面加上echo吗?
  • 你确定命令成功了吗?尝试将输出捕获到变量,打印变量,然后针对 grep 运行它。所以,output=$(timeout 2s curl -v telnet://"$element":22 2>&1); echo $output; if echo $output | grep "Connected to"; then ...
  • 当我在shell上直接运行curl命令时,就成功了
  • 它似乎正在工作,但if echo $output 正在生成大量文本。我应该添加/dev/null 来抑制它吗?您也可以更新答案,以便对其他人也有帮助。谢谢!!
【解决方案2】:

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 是一个很好的参考。

【讨论】:

    猜你喜欢
    • 2014-11-03
    • 2019-10-12
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2014-05-25
    • 2015-11-01
    • 2017-07-09
    相关资源
    最近更新 更多