telnet后关闭curl连接

tzcvj98z  于 2023-03-03  发布在  其他
关注(0)|答案(2)|浏览(194)

我想要的:

连接成功后,我希望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 (Disable keepalive use on the connection)
--connect-timeout (SECONDS Maximum time allowed for connection)
--keepalive-time (SECONDS Wait SECONDS between keepalive probes)

4xrmg8kj

4xrmg8kj1#

要使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替换为除TTYPEXDISPLOCNEW_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

1u4esq0p

1u4esq0p2#

对我有效的方法是发送“exit”到telnet,由于您对输出不感兴趣,请重定向它

$ echo "exit" | curl --connect-timeout 1 -s telnet://google.com:443 > /dev/null
$ echo $?
0
$ echo "exit" | curl --connect-timeout 1 -s telnet://google.com:4433 > /dev/null
$ echo $?
7

相关问题