简体   繁体   English

Bash 使用 telnet 和 netcar 检查与 host:port 的连接的脚本

[英]Bash script that check connection with host:port using telnet and netcar

I have task to create quite complicated bash script, which at first part is checking the connection to host:port with telnet and- if telnet would fail or would not be installed, try the connection using netcat.我的任务是创建相当复杂的 bash 脚本,该脚本首先是使用 telnet 检查与 host:port 的连接,如果 telnet 失败或无法安装,请尝试使用 netcat 进行连接。

I have problem with loop, where it will skip netcat if telnet would connect to the host and also, if both- telnet and netcat would fail- script would finish with error message.我有循环问题,如果 telnet 将连接到主机,它将跳过 netcat,而且,如果 telnet 和 netcat 都失败,则脚本将完成并显示错误消息。 The script:剧本:

#!/bin/bash
echo Type host IP address
read REMOTEHOST
echo Type port number
read REMOTEPORT
TIMEOUT=5

echo quit | timeout --signal=9 5 telnet $REMOTEHOST $REMOTEPORT


if nc -w $TIMEOUT -z $REMOTEHOST $REMOTEPORT; then
    echo "I was able to connect to ${REMOTEHOST}:${REMOTEPORT}"
else
    echo "Connection to ${REMOTEHOST}:${REMOTEPORT} failed. Exit code from Netcat was ($?)."
fi

You can use the $?你可以使用 $? variable to get the exit code from the last command.变量以从最后一个命令中获取退出代码。

I found that your original telnet command exits with error code 1 on my system because the escape character is ^].我发现您原来的 telnet 命令在我的系统上以错误代码 1 退出,因为转义字符是 ^]。 When I telnet manually I need to hit ctrl-] to enter the telnet prompt, then I can enter 'quit'.当我手动远程登录时,我需要按 ctrl-] 进入远程登录提示,然后我可以输入“退出”。

The trick here is you cannot just type ^], you have to type ctrl-v ctrl-]这里的诀窍是你不能只输入 ^],你必须输入 ctrl-v ctrl-]
ctrl-v tells the system to capture the next ctrl character. ctrl-v 告诉系统捕获下一个 ctrl 字符。

The following gives me an exit code of 0, and you can verify by running it manually with echo $?下面给我一个退出代码 0,您可以通过使用 echo $ 手动运行它来验证它? at the command line在命令行

-- remember to use ctrl-v ctr-] -- 记得使用 ctrl-v ctr-]

$ (echo ^]; echo quit) | timeout --signal=9 5 telnet <REMOTEHOST> <REMOTEPORT>  
$ echo $?

Then you can use this in your script:然后你可以在你的脚本中使用它:

#!/bin/bash
echo Type host IP address
read REMOTEHOST
echo Type port number
read REMOTEPORT
TIMEOUT=5
    
(echo ^]; echo quit) | timeout --signal=9 5 telnet $REMOTEHOST $REMOTEPORT > /dev/null 2>&1    
TELNET_EXIT_CODE=$?
    
if [[ $TELNET_EXIT_CODE -ne 0 ]]; then
    nc -w $TIMEOUT -z $REMOTEHOST $REMOTEPORT > /dev/null 2>&1
    NC_EXIT_CODE=$?
fi

if [[ $TELNET_EXIT_CODE -eq 0 ]] || [[ $NC_EXIT_CODE -eq 0 ]]; then
    echo "success"
else
    echo "fail"
fi

Tested on Ubuntu 20.04.04, GNU bash version 5.0.17, Telnet version 0.17-41在 Ubuntu 20.04.04、GNU bash 版本 5.0.17、Telnet 版本 0.17-41 上测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM