在我们监控服务器的应用状态或服务器的端口状态异常时,经常需要发送告警信息给管理员,发送告警信息基本上要么以邮件、短息、微信、及其他方式告知管理员。现在使用钉钉软件的企业也开始逐渐增多,其中钉钉有一个机器人发送功能,可以做到机器人向钉钉指定用户发送消息。发送消息没有上限、而且免费,有了这个功能我们就可以使用钉钉机器人向系统管理员用户发送告警消息。
我这里有一台监控服务器,用来跑PHP监控脚本,PHP监控脚本每隔5分钟向主服务器请求一个状态文件,更具请求过来的状态文件进行判断主服务器状态是否正常,如果状态正常,则在每日上午9:30向管理员发送一条状态正常的消息,异常状态则直接发送。
代码如下:
//获取主服务器状态文件
function curl_html(){
$ch = curl_init("http://www.xxx.asia/html/nginx-status.log") ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
$output = curl_exec($ch) ;
curl_close($ch);
$get_str = strlen($output);
return $get_str;
}
//获取钉钉token
function get_token(){
$url="https://oapi.dingtalk.com/gettoken?corpid=dinge1232db356e4a99&corpsecret=e9e4w__fryky95jOdcWfTaxvzeP2yLExenjOAC4sZuuyfVDk8yny8Wb_Ta12hr";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
$token = json_decode($output);
$obj_token = $token->{'access_token'};
return $obj_token;
}
//向钉钉端发送数据
function http_post_data($url, $data_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array($return_code, $return_content);
curl_close($ch);
}
$obj_token = get_token(); //获取token
$obj_status = curl_html(); //获取主服务器状态
$send_url = "https://oapi.dingtalk.com/chat/send?access_token=".$obj_token;
$chatid = "chate278923e931bb9bb36663bfebc9812a7"; //机器人ID
$sender = "0497593446775";
$get_date = date("H:i");
if($get_date == "09:30"){
if($obj_status > "1"){
$content = "时间: ".date("Y-m-d H:i:s")."\r\n平台Web服务异常,速请管理员处理!";
$post_data = json_encode(array ("chatid" => $chatid,"sender" => $sender,"msgtype"=>"text","text"=>array("content"=>$content)));
list($return_code, $return_content) = http_post_data($send_url, $post_data);
die();
}else{
$content = "时间: ".date("Y-m-d H:i:s")."\r\n平台Web服务状态正常";
$post_data = json_encode(array ("chatid" => $chatid,"sender" => $sender,"msgtype"=>"text","text"=>array("content"=>$content)));
list($return_code, $return_content) = http_post_data($send_url, $post_data);
die();
}
}
if($obj_status > "1"){
$content = "时间: ".date("Y-m-d H:i:s")."\r\n平台Web服务异常,速请管理员处理!";
$post_data = json_encode(array ("chatid" => $chatid,"sender" => $sender,"msgtype"=>"text","text"=>array("content"=>$content)));
list($return_code, $return_content) = http_post_data($send_url, $post_data);
}
消息发送如图:
转载于:https://blog.51cto.com/linuxinfo/1852432