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
Alternative in CentOS 7 for "nc -z"
提问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 nc
command (CentOS 6 seems to use Netcat and CentOS 7 uses another thing called Ncat) and now the -z
switch 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 nc
page 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 nc
CentOS 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