自动退出 Telnet 命令回到提示符,无需人工干预 ^] quit close exit code 1

Auto exit Telnet command back to prompt without human intervention ^] quit close exit code 1

我在主机上针对给定端口(已打开)运行ning telnet 命令,它 returns 0(成功)。

为了手动尝试 telnet,我键入以下命令,然后按 control+bracket 即 ^],然后按 Enter 键,然后我进入 telnet> 提示符,其中如果我键入 closequit,它会返回到 $ 提示符并且看到最后一个命令的退出状态显示 0 for (success) 因为端口 2878 是打开的(如根据 telnet 命令的输出)。

[vagrant@myvagrant /tmp] $ telnet `hostname` 2878
Trying 127.0.0.1...
Connected to myvagrant.
Escape character is '^]'.
^]

telnet> close
Connection closed.
[vagrant@myvagrant /tmp] $ echo $?
0

现在,我想在没有任何人为干预的情况下 运行 相同的操作,即我不想手动输入 ^] 并按 Enter 键来 telnet>提示符,然后输入close(或quit)telnet命令,最后回到$提示符。

为此,我尝试使用 echo -e 命令的选项并给出 ^]\n(用于换行符,即 Enter 键)和 close命令(对于 telnet> 提示,以便我返回到 $ 提示)。这样做,有点像预期的那样工作,但对于最后一个命令 echo $? 的退出状态,我得到 1(而不是 0)。 为什么?

[vagrant@myvagrant /tmp] $ echo -e "^]\nclose" | telnet `hostname` 2878
Trying 127.0.0.1...
Connected to myvagrant.
Escape character is '^]'.
Connection closed by foreign host.
[vagrant@myvagrant /tmp] $ 
[vagrant@myvagrant /tmp] $ echo $?
1
[vagrant@myvagrant /tmp] $ 

也尝试了 here-doc 方法,但不确定为什么它返回 1(作为退出代码)用于打开的有效端口。

[vagrant@myvagrant /tmp] $ telnet `hostname` 2878 <<GIGA
> echo ^]
> echo close
> GIGA
Trying 127.0.0.1...
Connected to myvagrant.
Escape character is '^]'.
Connection closed by foreign host.
[vagrant@myvagrant ~/aks/always-latest-ws-sunny] $ echo $?
1
[vagrant@myvagrant ~/aks/always-latest-ws-sunny] $

如果端口打开并获得 0 作为退出代码,我如何自动退出 telnet?如果有办法捕获上一个命令的输出,可能是我可以 grep 'Connection closed by foreign host.' 字符串来标记它成功 (0).

您可能需要其他 linux 包,例如 expect 来实现您想要的。

如果不使用 Expect,我猜想使用 HERE 文档(<

[vagrant@myvagrant /tmp] $ telnet_result=$(telnet `hostname` 2878 <<GIGA
echo ^]
echo close
GIGA
); echo $telnet_result | grep "Escape character is '^]'"; echo $?
Connection closed by foreign host.
 Escape character is '^]'.
0
[vagrant@myvagrant /tmp] $ 

并且对于 bad/invalid/non-open 端口,同样给出 1(如预期的那样)。

[vagrant@myvagrant /tmp] $ telnet_result=$(telnet `hostname` 287811111 <<GIGA
echo ^]
echo close
GIGA
); echo $telnet_result | grep "Escape character is '^]'"; echo $?
telnet: connect to address 127.0.0.1: Connection refused
1
[vagrant@myvagrant /tmp] $ 
╭─ ~
╰» echo "^]close^M" | telnet localhost 22; echo $?
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

telnet> close
Connection closed.
0

要输入 ^]^M 字符,请分别按 ctrl+v ctrt+]ctrl+v ctrl+m

对上面 Matthew 提供的答案稍作改进,允许您在 shell 脚本中使用它:

$ echo -e '\x1dclose\x0d' | telnet google.com 80
Connected to google.com.
Escape character is '^]'.

telnet> close
Connection closed.
$ echo $?
0

这是最简洁的方法

echo -n | telnet `hostname` 2878

有关此行为的更多信息,请参阅此 link

我为此使用的方法:

我在列表中 做 对于列表 1 中的 j 做 睡眠 2|超时 --signal=9 3 telnet $i $j 完毕 完成