我想要的:
连接成功后,希望curl成功退出。我在容器内运行此命令,因此我希望 curl 命令成功退出,以便容器也能成功退出。
这是我的例子:
$ curl -v telnet://google.com:443/
* Trying 172.217.197.113...
* TCP_NODELAY set
* Connected to google.com (172.217.197.113) port 443 (#0)
我尝试过的选项:
不保持事件状态:
$ curl -v --no-keepalive telnet://google.com:443/
* Trying 172.217.197.102...
* TCP_NODELAY set
* Connected to google.com (172.217.197.102) port 443 (#0)
连接超时:
$ curl -v --connect-timeout 5 telnet://google.com:443/
* Trying 172.217.197.139...
* TCP_NODELAY set
* Connected to google.com (172.217.197.139) port 443 (#0)
保持事件时间:
$ curl -v --keepalive-time 5 telnet://google.com:443/
* Trying 172.217.197.139...
* TCP_NODELAY set
* Connected to google.com (172.217.197.139) port 443 (#0)
标志定义
--no-keepalive(禁止在连接上使用 keepalive)
--connect-timeout(SECONDS 允许连接的最长时间)
--keepalive-time(Keepalive 探测之间等待 SECONDS 秒)
最佳答案
要使 curl 在 telnet 连接成功后立即退出,请特意传递一个未知的 telnet 选项并测试退出代码为 48:
curl --telnet-option 'BOGUS=1' --connect-timeout 2 -s telnet://google.com:443 </dev/null
code=$?
if [ "$?" -eq 48 ]; then
echo "Telnet connection was successful"
else
echo "Telnet connection failed. Curl exit code was $code"
fi
我们故意将未知的 telnet 选项 BOGUS=1
传递给 curl 的 -t, --telnet-option
选项。将 BOGUS
替换为除 TTYPE
、XDISPLOC
或 NEW_ENV
三个受支持选项之外的任何名称。
48 是 的 curl 错误代码“CURLE_UNKNOWN_OPTION (48) 无法识别/未知传递给 libcurl 的选项。”
之所以可行,是因为只有在成功连接后才会处理 telnet 选项。
轻微变化
故意传递语法错误的 telnet 选项,例如 BOGUS
或空字符串,并测试退出代码 49 ( CURLE_SETOPT_OPTION_SYNTAX )。我们在以下函数中使用这种方法。和以前一样,这是可行的,因为 curl 仅在成功连接后才处理 telnet 选项。
形式化为函数
# Args:
# 1 - host
# 2 - port
tcp_port_is_open() {
local code
curl --telnet-option BOGUS --connect-timeout 2 -s telnet://"$1:$2" </dev/null
code=$?
case $code in
49) return 0 ;;
*) return "$code" ;;
esac
}
测试
tcp_port_is_open example.com 80
echo "$?"
# 0 ✔️
tcp_port_is_open example.com 1234
echo "$?"
# 28 - Operation timeout ✔️
tcp_port_is_open nonexistent.example.com 80
echo "$?"
# 6 - Couldn't resolve host. ✔️
编辑:2022 年 5 月 27 日:观看此待办事项
https://curl.se/docs/todo.html#exit_immediately_upon_connection
通过:https://curl.se/mail/archive-2022-04/0027.html
关于curl - telnet 后关闭 curl 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64106136/