PHP 检查服务器是否存活
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7792413/
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
PHP checking if server is alive
提问by Saulius Antanavicius
I need to check if a group of servers, routers and switches is alive. I have been searching for something reliable that would work with IPs and ports for over an hour now, could anyone help?
我需要检查一组服务器、路由器和交换机是否处于活动状态。一个多小时以来,我一直在寻找可以与 IP 和端口一起使用的可靠东西,有人可以帮忙吗?
Ended up using
结束使用
function ping($addr, $port='') {
if(empty($port)) {
ob_start();
system('ping -c1 -w1 '.$addr, $return);
ob_end_clean();
if($return == 0) {
return true;
} else {
return false;
}
} else {
$fp = fsockopen("udp://{$addr}", $port, $errno, $errstr);
if (!$fp) {
return false;
} else {
return true;
}
}
}
回答by sdolgy
Servers, routers and switches...the one commonality that all of them share is the ability to accept SNMP requests if an SNMP service is running. Sounds like what you are trying to do is implement a funny workaround to a monitoring system (nagios, etc....)
服务器、路由器和交换机……它们共有的一个共同点是在 SNMP 服务正在运行时能够接受 SNMP 请求。听起来您想要做的是对监控系统(nagios 等...)实施一个有趣的解决方法
As per: http://php.net/manual/en/book.snmp.php
根据:http: //php.net/manual/en/book.snmp.php
<?php
$endpoints = array('10.0.0.1','10.0.0.2','10.0.0.3','10.0.0.4','10.0.0.5');
foreach ($endpoints as $endpoint) {
$session = new SNMP(SNMP::VERSION_2c, $endpoint, 'boguscommunity');
var_dump($session->getError());
// do something with the $session->getError() if it exists else, endpoint is up
}
?>
This will tell you if the endpoint is alive and the SNMP service is running. Specific to seeing if the port is available / open, you can use fsockopen()
:
这将告诉您端点是否处于活动状态并且 SNMP 服务是否正在运行。具体到查看端口是否可用/打开,可以使用fsockopen()
:
http://php.net/manual/en/function.fsockopen.php
http://php.net/manual/en/function.fsockopen.php
<?php
$fp = fsockopen("udp://127.0.0.1", 13, $errno, $errstr);
if (!$fp) {
echo "ERROR: $errno - $errstr<br />\n";
}
?>
回答by vzwick
$ip = "123.456.789.0";
$ping = exec("ping -c 1 -s 64 -t 64 ".$ip);
var_dump($ping);
// and so forth.
回答by Mike Q
if you are checking for mysql you can use something like
如果你正在检查 mysql 你可以使用类似的东西
if (mysqli_ping($ip)) echo "sweet!";
else echo "oh dam";
I would be a little concerned using the ping option as that can be blocked, and out of no where ...
我会有点担心使用 ping 选项,因为它可以被阻止,而且无处不在......