Cacti發送Slack告警訊息到不同頻道的方式,基本上也是寫程式去做正規化表示式的過濾與條件式的判斷,前置作業可以參考先前寫的Cacti整合Slack發送告警訊息,接著要把thold_functions.php第2847行裡面的 escapeshellarg($message)改成escapeshellarg($subject) ,先改好讓發送的訊息內容為郵件的標題,這樣比較方便程式去做正規化表示式的過濾與條件式的判斷。
接著編輯這個檔案
[root@Localhost ~]#vi /var/www/html/cacti/plugins/thold/slack.php
新版的程式內容如下,依照個人需求,改到自己需要發送的頻道即可。
程式如下
<?php
/*
以下程式字串條件式判斷式,是使用正規化表示式與模糊比對的方式設計的,依照Cacti告警標題設計好的比對順序發送到特定頻道
*/
//定義此區Cacti發送的圖示與帶入的發送名字
$username = "Cacti-TEST(網管系統)" ;
$icon_emoji = ":lion_face:" ;
//以下程式段落為針對資安設備IPS與WAF的字串過濾,並發送到專用的資安設備告警頻道(#test-security)
//此處的比對[**有分**大小寫]
if (preg_match("/(WAF)|(IPS)|(SMS)|(waf)|(ips)|(sms)/", $argv[1])) {
$data = array("username" => "$username","icon_emoji" => "$icon_emoji" ,"text" => "$argv[1]" ,"channel" => "#test-security");
$data_string = json_encode($data);
$url = "https://hooks.slack.com/services/RBCD0S7D/BHB4TGXQ/faBCfqYN5IkupUY3AKG";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
echo curl_exec($c);
}
//以下程式段落針對線路有關的字串過濾,並發送到專用的線路告警頻道(#test-circuit)
//此處的比對[**不分**大小寫]
elseif (preg_match("/(海纜)|(流量)|(公網)|(對點IP)|(P2P)|(IPsec)|(avg)|(OSPF)|(專線)|(BGP)|(Loopback)|(線路)|(上網)/i", $argv[1])) {
$data = array("username" => "$username","icon_emoji" => "$icon_emoji" ,"text" => "$argv[1]" ,"channel" => "#test-circuit");
$data_string = json_encode($data);
$url = "https://hooks.slack.com/services/RBCD0S7D/BHB4TGXQ/faBCfqYN5IkupUY3AKG";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
echo curl_exec($c);
}
//以下程式段落為如果上面字串都不符合的話,就發送到原本預設的頻道(#test-channel)
else{
$data = array("username" => "$username","icon_emoji" => "$icon_emoji" ,"text" => "$argv[1]" ,"channel" => "#test-channel");
$data_string = json_encode($data);
$url = "https://hooks.slack.com/services/RBCD0S7D/BHB4TGXQ/faBCfqYN5IkupUY3AKG";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($c, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($c, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
echo curl_exec($c);
}
?>
最後要測試程式的字串過濾是否正確的話,可以直接對程式帶入tholdhold送出來帶入的引數$argv[1] 來測試發送結果
[root@Localhost ~]# php /var/www/html/cacti/plugins/thold/slack.php "想要發送的文字"
符合預期的話,就代表正規化語法正確與程式的判斷式正確,可以拆開很多不同的頻道發告警,只要把想拆開的條件再用php的條件判斷語句再加入即可
沒有留言:
張貼留言