如何在 Shell 脚本的变量中捕获 telnet 命令的输出

How to capture the output of telnet command in a variable in Shell script

我需要使用 shell 脚本在远程服务器上 运行 telnet 命令并且必须捕获输出。当我执行下面的命令时,它没有完成,而是被挂起。有人可以建议如何在执行后使用 shell 脚本终止或超时 telnet 命令。

telnet_output=`telnet $server $port`
echo "Output is $telnet_output"

我也试过将它写入文件。但是在远程服务器上执行时也会挂起。

opfile="telop.log"
telnet_output=`telnet $server $port | tee $opfile`
op=`cat $opfile`
echo "$op"

试试这个:

telnet_output="$({ sleep 1; echo $'\e'; } | telnet $server $port 2>&1)"
printf "Output is\n%s\n" "$telnet_output"

echo $'\e'telnet 发送转义字符以终止它。