【问题标题】:Alternative in CentOS 7 for "nc -z"CentOS 7 中“nc -z”的替代方案
【发布时间】:2016-08-08 09:44:32
【问题描述】:

我有一个 bash 程序来检查给定端口中的守护进程是否正在工作:

nc -z localhost $port > /dev/null
if [ "$?" != "0" ]
then
  echo The server on port $port is not working
  exit
fi

这个程序在 CentOS 6 中完美运行。然而,似乎 CentOS 7 改变了 nc 命令的底层实现(CentOS 6 似乎使用 Netcat 而 CentOS 7 使用另一个叫做 Ncat 的东西)现在 -z开关不起作用:

$ nc -z localhost 8080
nc: invalid option -- 'z'

查看 CentOS 7 中的 man nc 页面,我没有看到任何明确的替代 -z。关于如何修复我的 bash 程序以使其在 CentOS 7 中运行的任何建议?

【问题讨论】:

  • 关于已经提出的关闭标志,让我澄清一下问题关于编程(特别是bash编程)。
  • 如果您不关心您正在使用的工具,您可以使用stackoverflow.com/questions/4922943/…的答案
  • if [ "$?" != "0" ] 是一种反模式;你只想要if nc -z localhost $port > /dev/null
  • 是的,这可能是一个改进。但是,底线(以及我的问题所关注的主题)是 -z 不适用于 CentOS 7 中的 nc 命令(实际上是 Ncat 的符号链接)。
  • 我的answer 涵盖了它并且也有示例。

标签: bash centos7 netcat


【解决方案1】:

还有一个你真正想要的精简版:

#!/bin/bash
# Start command: nohup ./check_server.sh 2>&1 &

check_server(){ # Start shell function

checkHTTPcode=$(curl -sLf -m 2 -w "%{http_code}\n" "http://10.10.10.10:8080/" -o /dev/null)

if [ $checkHTTPcode -ne 200 ]
    then
        # Check failed. Do something here and take any corrective measure here if nedded like restarting server
        # /sbin/service httpd restart >> /var/log/check_server.log
        echo "$(date) Check Failed " >> /var/log/check_server.log

    else
        # Everything's OK. Lets move on.
        echo "$(date) Check OK " >> /var/log/check_server.log
fi
}

while true # infinite check
do
# Call function every 30 seconds
check_server
sleep 30

done

【讨论】:

    【解决方案2】:

    根据this post,我用过:

    nc -w1 localhost $port < /dev/null
    

    (debian 也可以,但比nc -z 慢)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-16
      • 2019-12-15
      • 2019-07-07
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 2016-06-23
      相关资源
      最近更新 更多