我正在实习,我必须监视特定交换机的特定端口。如果端口连续多次断开连接,我决定发送电子邮件警报。为此,我已经在MySQL CLI中测试了此查询:
SELECT IF ((SELECT COUNT(message) FROM devices, ports, eventlog
WHERE hostname = "HOSTNAME"
AND message = "ifOperStatus: down -> up"
AND ports.ifName = "0/8" and datetime >= now() - INTERVAL 45 MINUTE) >= 4, "ok", "false");
如果事件日志消息“ ifOperStatus:向下->向上”出现4次或+,则查询返回“确定”。
现在,我想编写一个连接到我的数据库的脚本,执行上一个查询,如果返回“ ok”,则发送电子邮件。我将设置一个cron作业以每分钟自动执行脚本。
问题是,我不知道该怎么做。我已经测试过了:
#!/usr/bin/php
<?php
//connect to database
$dbconnect = mysql_connect('HOSTNAME', 'DB_Name', 'Passwd');
$result = $dbconnect->query(
SELECT IF ((SELECT COUNT(message) FROM devices, ports, eventlog
WHERE hostname = "HOSTNAME"
AND message = "ifOperStatus: down -> up"
AND ports.ifName = "0/8" and datetime >= now() - INTERVAL 1 DAY) >= 4, "good",
"false"
);
//if there are any records matching this query we send an email listing each one using 'part_no' as the identifier in this case
if ($result = 'good') {
$email = 'destination_mail';
$subject = "Port alert";
$message = "Port go down too much";
if (mail($email, $subject, $message)) {
// mail successfully sent
} else {
// mail unsuccessfull
}
}
我真的很难写脚本。感谢您的帮助。