使用PHP制作主机宕机检测,并发送Mail通知
来源:互联网 发布:逆战卡数据教程 编辑:程序博客网 时间:2024/06/08 02:57
这是在公司时候的一段代码,宕机检测的原理,就只有检测是否能够ping通主机,如果不通发送mail,这只是我能想到的办法,有大神如果能想到更好的检测办法,不吝赐教!
OK,废话少说,翠花,上代码!
(ps:代码中用到了PHPMailer,参考的人,请下载打包代码吧~)
- <?php
-
-
-
-
-
- set_time_limit(0);
- define('ROOT', dirname(__FILE__) . DIRECTORY_SEPARATOR);
-
- $ipAddress = '45.33.36.121';
-
- $file = ROOT . 'sendMailTime.txt';
-
- file_put_contents($file, 0);
- if (file_exists($file)) {
-
- while (true) {
-
- $hostStatus = pingAddress($ipAddress);
- if (!$hostStatus) {
- $lastTime = (int) file_get_contents($file);
-
- if (time() - $lastTime > 3600) {
- $row = sendMail([
- 'subject' => "{$ipAddress}主机宕机警告",
- 'body' => "dear,{$ipAddress}主机已经宕机,请知晓,发送时间:" . date('Y-m-d H:i:s'),
- 'address' => [
- [
- 'name' => 'Stronger',
- 'email' => 'stronger@sinoangel.cn'
- ],
- [
- 'name' => '李星',
- 'email' => 'lixing@sinoangel.cn'
- ]
- ]
- ]);
- if ($row) {
- file_put_contents($file, time());
- }
- }
- }
- sleep(10);
- }
- } else {
- exit("fail");
- }
-
-
-
-
-
-
- function sendMail($config = []) {
- require ROOT . 'PHPMailer/PHPMailerAutoload.php';
- $mail = new PHPMailer;
- $mail->isSMTP();
- $mail->Host = 'smtp.qq.com';
- $mail->SMTPAuth = true;
- $mail->CharSet = "UTF-8";
- $mail->setLanguage('zh_cn');
- $mail->Username = 'server@sinoangel.cn';
- $mail->Password = 'ss123456';
- $mail->SMTPSecure = 'tls';
- $mail->Priority = 1;
- $mail->From = 'server@sinoangel.cn';
- $mail->FromName = 'SinoAngel-Server';
- if (!isset($config['address']) || empty($config['address'])) {
- return false;
- }
-
- $address = $config['address'];
- if (isset($address['name']) && isset($address['email'])) {
- if (empty($address['name']) || empty($address['email'])) {
- return false;
- }
- $mail->addAddress($address['email'], $address['name']);
- } else {
- foreach ($address as $addKey => $addVal) {
- if (!empty($addVal['email']) && !empty($addVal['name'])) {
- $mail->addAddress($addVal['email'], $addVal['name']);
- }
- }
- }
- $mail->WordWrap = 50;
-
- if (isset($config['file']) && !empty($config['file'])) {
- if (is_string($config['file'])) {
- $mail->addAttachment($config['file']);
- } elseif (is_array($config['file']) && !empty($config['file'])) {
- foreach ($config['file'] as $file) {
- $mail->addAttachment($file);
- }
- }
- }
- $mail->isHTML(true);
-
- if (isset($config['subject']) && !empty($config['subject'])) {
- $mail->Subject = $config['subject'];
- }
-
- if (isset($config['body']) && !empty($config['body'])) {
- $mail->Body = $config['body'];
- }
- return $mail->send();
- }
-
-
-
-
-
-
- function pingAddress($address) {
- $status = -1;
- if (strcasecmp(PHP_OS, 'WINNT') === 0) {
-
- $pingresult = exec("ping -n 1 {$address}", $outcome, $status);
- } elseif (strcasecmp(PHP_OS, 'Linux') === 0) {
-
- $pingresult = exec("ping -c 1 {$address}", $outcome, $status);
- }
- if (0 == $status) {
- $status = true;
- } else {
- $status = false;
- }
- return $status;
- }
0 0