bash CentOS 7 中“nc -z”的替代方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36663738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:30:41  来源:igfitidea点击:

Alternative in CentOS 7 for "nc -z"

bashcentos7netcat

提问by fgalan

I have a bash program that checks that a daemon in a given port is working:

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

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

This program works perfectly in CentOS 6. However, it seems that CentOS 7 has changed the underlying implementation for nccommand (CentOS 6 seems to use Netcat and CentOS 7 uses another thing called Ncat) and now the -zswitch doesn't work:

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

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

Looking to the man ncpage in CentOS 7 I don't see any clear alternative to -z. Any suggestion on how I should fix my bash program to make it work in CentOS 7?

查看man ncCentOS 7 中的页面,我看不到-z. 关于我应该如何修复我的 bash 程序以使其在 CentOS 7 中工作的任何建议?

回答by mjoao

And a trimmed down version for what you really want:

以及您真正想要的精简版:

#!/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

回答by kyodev

according this post, I used:

根据这篇文章,我使用了:

nc -w1 localhost $port < /dev/null

( this work on debian too, but it's slower than nc -z)

(这也适用于 debian,但比 慢nc -z