从bash捕获telnet超时 [英] Capturing telnet timeout from bash
问题描述
引用此问题:使用bash脚本自动进行telnet会话
我正在尝试捕获远程主机超时所花费的时间.假设是10秒.手动,我可以启动 time telnet主机端口
输入一些命令,然后不执行任何操作,并且在10秒钟后, time
的输出将保存我所需的时间.
I am trying to capture the time it takes for a remote host to timeout.
Let's say it's 10 seconds.
By hand, I can launch time telnet host port
input some commands and then do nothing and after 10 seconds time
's output will hold my needed time.
在脚本中,问题在于使用此解决方案:
While, in a script, the issue is that using this solution:
{ echo "command"; } | time telnet host port
当管道结束时,它将发送EOF,并且telnet立即关闭.我可以通过添加一个
when the pipes end, it sends an EOF and telnet closes immediately. I can solve this by adding a sleep n
as my last piped command, but then everything hangs for that timeout (which can be more than the actual server timeout).
仅说明一下我要做什么,所以让我们借用Google的帮助.我希望我的时间输出为5分钟,这就是Google似乎用作超时的时间.相反:
Just to explain what I'm trying to do let's borrow Google's help. I want my time output to be 5 minutes, which is what Google seems to use as timeout. Instead:
{ echo "GET / HTTP/1.1"; echo "Host: www.google.com"; echo "Connection: keep-Alive"; echo ""; echo ""; } | time telnet www.google.com 80 2>&1
给出 0
-错误(立即发送EOF)
Gives 0
- wrong (EOF is sent immediately)
{ echo "GET / HTTP/1.1"; echo "Host: www.google.com"; echo "Connection: keep-Alive"; echo ""; echo ""; sleep 10; } | time telnet www.google.com 80 2>&1
给出 10
-错误
{ echo "GET / HTTP/1.1"; echo "Host: www.google.com"; echo "Connection: keep-Alive"; echo ""; echo ""; sleep 1; } | time telnet www.google.com 80 2>&1
给出 1
-错误
{ echo "GET / HTTP/1.1"; echo "Host: www.google.com"; echo "Connection: keep-Alive"; echo ""; echo ""; sleep 900; } | time telnet www.google.com 80 2>&1
给出 900
-错误(在这里,如果远程主机发送了kill命令,那么我希望telnet停止,但是睡眠会获胜)
Gives 900
- wrong (here I would expect the telnet to stop given the remote host sends a kill, but instead the sleep wins)
那么,我该如何解决呢?谢谢!
So, how can I solve this? Thanks!
推荐答案
尽管我不太喜欢它,但这似乎可行:
Although I don't overly like it, this seems to work:
( time { echo "set timeout 400"; echo "spawn telnet www.google.com 80";
echo 'send "GET / HTTP/1.1\r"'; echo "send \"Host: www.google.com\r\"";
echo 'send "Connection: keep-alive\r"'; echo 'send "\r"';
echo "expect { eof exit timeout exit }"; } | expect ) 2>&1
上面的代码同时输出HTTP标头/正文和时间结果,因此都可以对其进行操作.
The above outputs both the HTTP headers/body and the time results, so both can be manipulated.
顺便说一句,以上内容适用于HTTP.对于HTTPS,您必须使用openssl,但是可以使用相同的系统.
By the way, the above works for HTTP. For HTTPS you have to use openssl, but the same system works.
这篇关于从bash捕获telnet超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!