原理
由於 cacti 的 thold 外掛外掛本身並沒有微信告警功能,只有郵件功能,所以本文章的微信告警功能其實是有取巧的性質。原理就是在 thold 外掛外掛觸發郵件告警的時候,同時執行微信傳送訊息的指令碼,利用微信公眾號的 api 傳送告警內容。
配置(cacti 目錄為/usr/local/cacti)
1:安裝 cacti 的 thold 與 settings 外掛外掛。
thold 依賴 setting 外掛外掛,先安裝 settings 外掛外掛:
外掛外掛下載地址:http://docs.cacti.net/plugin:settings
1
2
# cp settings-v0.71-1.tgz /usr/local/cacti/plugins
# tar -zxvf settings-v0.71-1.tgz
安裝 thold 外掛外掛:
外掛外掛下載地址:http://docs.cacti.net/plugin:thold
1
2
# cp thold-v0.5.0.tgz /usr/local/cacti/plugins
# tar -zxvf thold-v0.5.0.tgz
使外掛外掛生效:
1
2
3
4
5
6
7
8
9
10
11
12
# vi /usr/local/cacti/include/config.php
$database_type = “mysql”;
$database_default = “cacti”;
$database_hostname = “localhost”;
$database_username = “cacti”;
$database_password = “cacti123456”;
$database_port = “3306”;
$database_ssl = false;
#新增如下資訊
$plugins[] = ‘settings’;
$plugins[] = ‘thold’;
進入 cacti,在 console–Configuration–Plugin Management 中開啟外掛外掛即可。
2:配置微信告警觸發與微信告警指令碼
在 thold 外掛外掛程式中,觸發郵件告警的部分,新增執行微信告警的程式碼。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# vi /usr/local/cacti/plugins/thold/thold_functions.php
$message = str_replace(‘
Could not open!
” . $val[‘file’], $message);
}
}
}
########找到相關程式碼位置,新增如下程式碼__start#####################
$msg_wx = strip_tags(str_replace(‘
‘, “n”, $message)); //刪除 message 中的 html 標籤, 並將
替換為換行符 n
$msg_wx = trim($msg_wx); //整理 msg_wx 字串
$msg_wx = iconv( “GB2312//IGNORE”, “UTF-8”, $msg_wx); //轉換編碼為 utf-8,防止亂碼
$sub_wx = iconv( “GB2312//IGNORE”, “UTF-8”, $subject); //轉換編碼為 utf-8,防止亂碼
$file_title = ‘/tmp/title.txt’; //要寫入檔案的檔名(可以是任意檔名),如果檔案不存在,將會建立一個
$file_message = ‘/tmp/message.txt’; //要寫入檔案的檔名(可以是任意檔名),如果檔案不存在,將會建立一個
if($f = file_put_contents($file_title, $sub_wx)) //將 subject 引數的值儲存到 file_title 中
if($f = file_put_contents($file_message, $msg_wx)) //將 msg_wx 引數的值儲存到 file_message 中
shell_exec(“/etc/wechat.sh”); //執行 wechat.sh 檔案,進行微信報警操作。
#################end#################################
$text = array(‘text’ => ”, ‘html’ => ”);
if ($filename == ”) {
$message = str_replace(‘
‘, “n”, $message);
$message = str_replace(‘
‘, “n”, $message);
$message = str_replace(‘‘, “n”, $message);
$text[‘text’] = strip_tags($message);
觸發微信訊息指令碼:(提前申請微信企業號,並配置好相關資訊,可參考博文 http://icenycmh.blog.51cto.com/4077647/1909527)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# vi /etc/wechat.sh
#微信企業號的 CropID
CropID=’xxxxxxxxxxxxxxx’
#企業號中傳送告警的應用
Secret=’xxxxxxxxxxxxxxxxxxxxxxxxxxx’
GURL=”https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$CropID&corpsecret=$Secret”
Gtoken=$(/usr/bin/curl -s -G $GURL | awk -F “[“: