telnet后关闭curl连接

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

我想要的:

连接成功后,我希望curl成功退出。我在一个容器中运行这个命令,所以我希望curl命令成功退出,这样容器也会退出。

下面是我的例子:

  1. $ curl -v telnet://google.com:443/
  2. * Trying 172.217.197.113...
  3. * TCP_NODELAY set
  4. * Connected to google.com (172.217.197.113) port 443 (#0)

我已尝试的选项:
否保持活动状态:

  1. $ curl -v --no-keepalive telnet://google.com:443/
  2. * Trying 172.217.197.102...
  3. * TCP_NODELAY set
  4. * Connected to google.com (172.217.197.102) port 443 (#0)

连接超时:

  1. $ curl -v --connect-timeout 5 telnet://google.com:443/
  2. * Trying 172.217.197.139...
  3. * TCP_NODELAY set
  4. * Connected to google.com (172.217.197.139) port 443 (#0)

保持活动时间:

  1. $ curl -v --keepalive-time 5 telnet://google.com:443/
  2. * Trying 172.217.197.139...
  3. * TCP_NODELAY set
  4. * 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:

  1. curl --telnet-option 'BOGUS=1' --connect-timeout 2 -s telnet://google.com:443 </dev/null
  2. code=$?
  3. if [ "$?" -eq 48 ]; then
  4. echo "Telnet connection was successful"
  5. else
  6. echo "Telnet connection failed. Curl exit code was $code"
  7. 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选项。

形式化为函数

  1. # Args:
  2. # 1 - host
  3. # 2 - port
  4. tcp_port_is_open() {
  5. local code
  6. curl --telnet-option BOGUS --connect-timeout 2 -s telnet://"$1:$2" </dev/null
  7. code=$?
  8. case $code in
  9. 49) return 0 ;;
  10. *) return "$code" ;;
  11. esac
  12. }

测试

  1. tcp_port_is_open example.com 80
  2. echo "$?"
  3. # 0 ✔️
  4. tcp_port_is_open example.com 1234
  5. echo "$?"
  6. # 28 - Operation timeout ✔️
  7. tcp_port_is_open nonexistent.example.com 80
  8. echo "$?"
  9. # 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,由于您对输出不感兴趣,请重定向它

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

相关问题