首頁>技術>

一、環境

系統:centos7elk 版本:7.6.2
1.1 ElastAlert 工作原理

週期性的查詢Elastsearch並且將資料傳遞給規則型別,規則型別定義了需要查詢哪些資料。

ElastAlert 手冊

二、安裝配置 elastalert

Tips:Elastalert 0.2.0 之後使用 Python 3.6,不再使用 Python 2 版本

2.1 安裝 python3.6
#安裝EPEL和IUS軟體源yum install epel-release -yyum install https://centos7.iuscommunity.org/ius-release.rpm -y#安裝python3.6yum install python36u python36u-devel python36u-pip -y#ln -s /usr/bin/python3.6 /bin/python3#ln -s /usr/bin/pip3.6 /bin/pip3
2.2 安裝 elastalert
pip3 install elastalert
2.2.1 配置
cd /opt/soft/git clone https://github.com/Yelp/elastalert.git cd elastalertcp config.yaml.example config.yamlmkdir rules
2.2.2 樣例

https://github.com/Yelp/elastalert/tree/master/example_rules

2.2.3 config.yaml 配置檔案
#規則目錄rules_folder: /opt/soft/elastalert/rules#多久從ES中查詢一次run_every:  seconds: 30#是查詢視窗的大小,從每個查詢執行的時間向後延伸。對於其中use_count_query或use_terms_query設定為true的規則,此值將被忽略。buffer_time:  minutes: 15#連線elasticsearch配置es_host: 127.0.0.1es_port: 9200es_username: elastices_password: xxxxxxxx#elastalert索引名稱writeback_index: elastalert_statuswriteback_alias: elastalert_alerts#失敗重試限制alert_time_limit:  days: 2  

**以下配置沒使用,只做介紹 **

#### 使用 TLS 連線誒 elastsearch#use_ssl: True#驗證 tls 證書#verify_certs: True#帶正文的GET請求是Elasticsearch的預設選項。如果因為某些原因失敗了,你可以透過'GET','POST'或'source',具體可以檢視以下(http://elasticsearch-py.readthedocs.io/en/master/connection.html?highlight=send_get_body_as#transport)#es_send_get_body_as: GET# 開啟 ssl 認證證書#verify_certs: True#ca_certs: /path/to/cacert.pem#client_cert: /path/to/client_cert.pem#client_key: /path/to/client_key.key
2.2.4 在 elasticsearch 中建立 elastalert 的日誌索引

**Tips : **如果索引已存在,則不會重新建立

elastalert-create-index --index elastalert

輸出結果:

ProcessController:  Elastic Version: 7.6.2Reading Elastic 6 index mappings:Reading index mapping 'es_mappings/6/silence.json'Reading index mapping 'es_mappings/6/elastalert_status.json'Reading index mapping 'es_mappings/6/elastalert.json'Reading index mapping 'es_mappings/6/past_elastalert.json'Reading index mapping 'es_mappings/6/elastalert_error.json'
2.3 常用命令
# 測試規則檔案elastalert-test-rule rule.yaml# 啟動監控報警python3 -m elastalert.elastalert --verbose --rule /root/elastalert/example_rules/rule.yaml
2.4 服務啟動方法

Tips: 啟動指定家目錄的原因主要是有呼叫,可以少寫路徑,比如不需要指定 config.yml,rule 裡面的 yml 檔案可以少寫路徑指定==

2.4.1 service 啟動管理
# 建立elastalert服務檔案vim /etc/systemd/system/elastalert.service
[Unit]Description=elastalertAfter=elasticsearch.service[Service]Type=simpleUser=rootGroup=rootRestart=on-failureWorkingDirectory=/opt/soft/elastalertExecStart=/usr/bin/python3 -m elastalert.elastalert --verbose --config /opt/soft/elastalert/config.yaml [Install]WantedBy=multi-user.target
2.4.2 supervisor 啟動管理

安裝supervisor

yum install -y supervisorsystemctl enable supervisord

編寫elastalert supervisord守護程序

vim /etc/supervisord.d/elastalert.ini

[program:elastalert]directory=/opt/soft/elastalertcommand=/usr/bin/python3 -m elastalert.elastalert --verboseautostart=truestartsecs=5autorestart=truestartretries=10redirect_stderr=truestdout_logfile_maxbytes=20MBstdout_logfile_backups=5stdout_logfile=/var/log/elastalert/elastalert.log

啟動

systemctl enable supervisordsystemctl restart supervisordsystemctl start supervisordsystemctl stop supervisordsupervisorctl status
三、告警測試3.1 es 測試索引3.1.1 建立並推送資料到 index

curl -X POST "http://elastic:passwd@127.0.0.1:9200/test-alert/test" -H 'Content-Type: application/json' -d '{"@timestamp": "'$(date --iso-8601=seconds)'", "field": "value"}'

輸出:

{"_index":"test-alert","_type":"test","_id":"inH1I3cBMJwNYi416aLN","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"_seq_no":0,"_primary_term":1}

輸出:

{"acknowledged":true}

3.1.3 檢視有哪些索引

curl 'http://elastic:passwd@127.0.0.1:9200/_cat/indices?v'

3.1.4檢視索引內容:

curl -X GET http://elastic:passwd@127.0.0.1:9200/test-alert/_search

輸出結果:

{"took":2,"timed_out":false,"shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":4,"relation":"eq"},"max_score":1.0,"hits":[{"index":"test-alert","type":"test","id":"inH1I3cBMJwNYi416aLN","score":1.0,"source":{"@timestamp": "2021-01-21T08:01:52+00:00", "field": "value"}},{"index":"test-alert","type":"test","id":"0ocXJHcBMJwNYi41y3rG","score":1.0,"source":{"@timestamp": "2021-01-21T08:37:55+0000", "field": "value"}},{"index":"test-alert","type":"test","id":"aZAiJHcBMJwNYi41QTqW","score":1.0,"source":{"@timestamp": "2021-01-21T08:49:20+0000", "field": "value"}},{"index":"test-alert","type":"test","id":"1ZMmJHcBMJwNYi41h4z8","score":1.0,"source":{"@timestamp": "2021-01-21T08:54:00+0000", "field": "value"}}]}}
3.2 郵件告警3.2.1 建立測試告警規則

vim /opt/soft/elastalert/rules/emailtt.yml

name: test-alerttype: any# es 的監控索引index: test-ale*# 發現 1 次就告警num_events: 1#1 分鐘檢查1次,和上面一起配合就是 1 分鐘內觸發 1 次規則就告警timeframe:  minutes: 1  #告警規則,查詢索引內 field 欄位的值 value,可以用正則進行匹配filter:- query:    query_string:      query: "field: *value*"      ## smtp 郵件 server 配置smtp_host: smtp.zoho.comsmtp_port: 465smtp_ssl: truefrom_addr: "test@qq.com"### 傳送郵件的賬號密碼smtp_auth_file: /opt/soft/elastalert/elastalert/smtp_auth_file.yml#告警方式alert:- "email"#設定只需要的告警欄位include: ["_index","uri","remote_addr","http_x_forwarded_for","status"]#郵件標題alert_subject: "test-alert 正式環境 告警 {}"#告警郵件接收人email:- "test@qq.com"- "test1@qq.comk"
3.2.2 傳送郵件的賬號密碼

vi /opt/soft/elastalert/elastalert/smtp_auth_file.yml

# 發件箱的qq郵箱地址,也就是使用者名稱user: test@qq.com# 不是qq郵箱的登入密碼,是授權碼password: passwd
3.2.3 啟動告警規則併發送測試資料
cd /opt/soft/elastalertpython3 -m elastalert.elastalert --verbose --rule /opt/soft/elastalert/rules/emailtt.yml
3.3 釘釘告警3.3.1 下載外掛
cd /opt/soft/elastalertgit clone https://github.com/xuyaoqiang/elastalert-dingtalk-plugincp elastalert-dingtalk-plugin/elastalert_modules/dingtalk_alert.py elastalert/
3.3.2 安裝依賴
#檢視依賴檔案elastalert-dingtalk-plugin/requirements.txt,在對比 pip list 之後,我發現只需要安裝以下內容即可pip3 install pyOpenSSL==16.2.0pip3 install requests==2.18.1pip3 install setuptools>=11.3
3.3.3 建立測試告警規則

vim /opt/soft/elastalert/rules/dingtt.yml

name: Example frequency ruletype: anyindex: test-alertnum_events: 1timeframe:  minutes: 1filter:- query:    query_string:      query: "field: value"#告警方式alert:- "elastalert.dingtalk_alert.DingTalkAlerter"#釘釘介面dingtalk_webhook: "https://oapi.dingtalk.com/robot/send?access_token=釘釘機器人 api token"dingtalk_msgtype: "text"
3.3.4 啟動告警規則併發送測試資料
cd /opt/soft/elastalertpython3 -m elastalert.elastalert --verbose --rule /opt/soft/elastalert/rules/dingtt.yml
3.3.5 釘釘機器人配置

具體可以檢視釘釘機器人開發文件

最簡單可以使用加 ip 方式加關鍵字,就是傳送到釘釘的資訊裡面有某個關鍵字3.3.6 測試結果告警內容如下所示

https://anjia0532.github.io/2017/02/16/elastalert-wechat-plugin/

https://github.com/anjia0532/elastalert-docker

3.5 告警格式最佳化
# 注意上下欄位對應alert_text: |    kibana_url: "https://hostname:5601/app/kibana"    alarm_reason: "1分鐘內login.php至少被訪問10次"    alarm_name: {}    request_uri: {}    request_ip: {}    response_status: {}alert_text_args:    - name    - request    - clientip    - responsealert_text_type: alert_text_only
四、kibana 新增 elastalert 外掛4.1 elastalert-kibana-plugin外掛

kibana中elastalert外掛,可以實現在kibana介面上編輯elastalert的告警規則配置。

kibana 的 elastalert 外掛需要使用新的 bitsensor/elastalert api 服務

4.1.1 演示效果4.2 安裝 elastalert-kibana-plugin

官網主推:bitsensor/elastalert-kibana-plugin

但是樓上那個很多小版本都沒有,以上沒有的話推薦使用以下版本:

nsano-rururu/elastalert-kibana-plugin

目前版本支援:

Kibana 6.8.1~6.8.12、7.5.1~7.8.1Kibana 7.9.0~7.9.34.2.1 安裝命令

/usr/share/kibana/bin/kibana-plugin install https://github.com/nsano-rururu/elastalert-kibana-plugin/releases/download/1.2.0/elastalert-kibana-plugin-1.2.0-7.6.2.zip --allow-root

4.2.2 配置

預設情況下,外掛將連線到 localhost:3030,也就是 kibana 和 elastalert 在同一臺伺服器上面,那麼就不需要新增以下配置。如果您的ElastAlert伺服器在其他主機或埠上執行,請在config / kibana.yml檔案中新增更改以下選項:

elastalert-kibana-plugin.serverHost: 192.168.1.1elastalert-kibana-plugin.serverPort: 9000
4.3 安裝 elastalert_docker

檢視 nsano 提供的 elastalert api 服務支援列表

我使用的是 praecoapp/elastalert-server 提供的 docker 映象對應 elastalert 0.2.4 版本

docker-compose sample 示例參考

4.3.1 安裝命令
cd /opt/soft/git clone https://github.com/bitsensor/elastalert.git elastalert_dockercd elastalert_dockermkdir rules 
4.3.2 更改配置,api server 端用的配置是config.json

vi config/config.json

因為我的 kibana 和 elastalert docker 是同一臺機,所以我主要修改 es 的配置就可以

{  "appName": "elastalert-server",  "port": 3030,  "wsport": 3333,  "elastalertPath": "/opt/elastalert",  "verbose": false,  "es_debug": false,  "debug": false,  "rulesPath": {    "relative": true,    "path": "/rules"  },  "templatesPath": {    "relative": true,    "path": "/rule_templates"  },  "es_host": "192.168.3.30",  "es_port": 9200,  "writeback_index": "elastalert_status"}
4.3.3 更改 elastalert 配置

vi ./config/elastalert.yaml

es_host: 192.168.3.30es_port: 9200rules_folder: rulesrun_every:  seconds: 5buffer_time:  minutes: 1es_username: elastices_password: passwdwriteback_index: elastalert_statusalert_time_limit:  days: 2
4.3.4 docker-compose.yml 配置檔案

vi docker-compose.yml

version: '3'services:  elastalert:    image: praecoapp/elastalert-server:20210104    container_name: elastalert    hostname: elastalert    restart: always    network_mode: "host"    ports:      - "3030:3030"      - "3333:3333"    volumes:      - ./config/elastalert.yaml:/opt/elastalert/config.yaml      - ./config/elastalert-test.yaml:/opt/elastalert/config-test.yaml      - ./config/config.json:/opt/elastalert-server/config/config.json      - ./rules:/opt/elastalert/rules      - ./rule_templates:/opt/elastalert/rule_templates      #- ./elastalert:/opt/elastalert/elastalert,#這一句先註釋掉,下面有個操作
4.3.5 啟動
docker-compose up -d##然後把 docker 映象裡面的 elastalert 複製出來docker cp elastalert:/opt/elastalert/elastalert .##再把docker-compose.yml 裡面的 volumes 的註釋項去掉重新啟動docker-compose up -d
4.3.6 配套釘釘外掛和規則測試
cd /opt/soft/elastalert_dockergit clone https://github.com/xuyaoqiang/elastalert-dingtalk-plugincp elastalert-dingtalk-plugin/elastalert_modules/dingtalk_alert.py elastalert/##安裝依賴docker exec -it elastalert pip install pyOpenSSL==16.2.0docker exec -it elastalert pip install requests==2.18.1docker exec -it elastalert pip install setuptools>=11.3#建立規則touch rules/dingtt.yml#授權,否則頁面無法編輯,具體可以看下面的報錯示例chown centos.centos rules/dingtt.yml#重新啟動 elastalert 容器docker restart elastalert##檢視日誌docker logs -f --tail=20 elastalert
4.4 出現的報錯:
01:50:07.285Z ERROR elastalert-server:    Routes:  Request for '/rules/:id' failed with error:          [Error: EACCES: permission denied, open '/opt/elastalert/rules/dingtt.yaml'] {      errno: -13,      code: 'EACCES',      syscall: 'open',      path: '/opt/elastalert/rules/dingtt.yaml'    }

解決辦法:

直接 chmod 777 -R /opt/soft/elastalert_docker/rules/直接 chown centos.centos /opt/soft/elastalert_docker/rules/*五、告警規則詳解

ElastAlert 規則介紹

5.1 告警型別
ElastAlert包含幾種具有常見監視範例的規則型別:any: 匹配任何與給定過濾器匹配的事件,這個是查到了什麼便直接報警,屬於自定義選項;frequency: 匹配Y時間內至少有X個事件的地方spike: 當事件發生率增加或減少時匹配,API 流量陡然上升並馬上恢復的時候;flatline: 在Y時間內少於X個事件時進行匹配,記憶體或者CPU使用率下降的時候;blacklist並whitelist輸入: 當某個欄位與黑名單/白名單匹配時匹配,昨天的那個疑似爬蟲的 IP 地址又出現了;change: 當某個欄位在一段時間內具有兩個不同的值時進行匹配,應用的狀態突然從 UP 轉為 DOWN;new_term: 當欄位中出現從未見過的術語時進行匹配,某個列舉型別欄位,突然出現了未定義的型別;cardinality:當欄位的唯一值數量大於或小於閾值時匹配,線上的 API 伺服器突然掛了一臺,它是根據唯一值的數量來判定的;
5.2 報警抑制:減少重複報警
# 用來區分報警,跟 realert 配合使用,在這裡意味著,# 5 分鐘內如果有重複報警,那麼當 name 不同時,會當做不同的報警處理,可以是陣列query_key:  - name# 5 分鐘內相同的報警不會重複傳送realert:  minutes: 5# 指數級擴大 realert 時間,中間如果有報警,# 則按照 5 -> 10 -> 20 -> 40 -> 60 不斷增大報警時間到制定的最大時間,# 如果之後報警減少,則會慢慢恢復原始 realert 時間exponential_realert:  hours: 1
5.3 報警聚合:相同報警,聚合為一條
# 根據報警的內,將相同的報警安裝 name 來聚合aggregation_key: name# 聚合報警的內容,只展示 name 與 messagesummary_table_fields:  - name  - message
5.4 報警格式化:突出重要資訊

在這裡,你可以自定義 alert 的內容,它的內部使用 Python 的 format 來實現的。

alert_subject: "Error {} @{}"alert_subject_args:  - name  - "@timestamp"alert_text_type: alert_text_onlyalert_text: |  ### Error frequency exceeds  > Name: {}  > Message: {}  > Host: {} ({})alert_text_args:  - name  - message  - hostname  - host
六、告警接收方式
EmailSlack企業微信釘釘alerta:https://github.com/alerta/alerta,告警接收平臺JIRAOpsGenieCommandsHipChatMS TeamsTelegramAWS SNSVictorOpsPagerDutyExotelTwilioGitter
七、告警需求整理

整理下實施ELK最起碼要實現的需求:

查詢條件(精確匹配):一級域名、二級域名、客戶真實IP、HTTP狀態碼、HTTP方法、request_time、response_time、代理IP、body_bytes_sent查詢條件(模糊匹配):url(如查詢SQL注入關鍵字)、refere(流量來源)、agent(如查詢搜尋引擎)近期(1周、1個月)內整體請求量走勢情況;如果發現總體走勢異常,要很方便找到那個域名走勢異常;過去一個週期內(1天、1周、1月)所有請求構成,按不同域名出餅圖;實時監控爬蟲IP過高的頻率訪問(如單個IP1分鐘請求超過100次報警);實時監控500狀態請求情況(如單個域名1分鐘出現30個500就報警);參考

https://github.com/Yelp/elastalert

https://github.com/bitsensor/elastalert

https://github.com/bitsensor/elastalert-kibana-plugin

https://github.com/xuyaoqiang/elastalert-dingtalk-plugin

https://github.com/anjia0532/elastalert-wechat-plugin

https://segmentfault.com/a/1190000017553282

https://blog.csdn.net/wenwenxiong/article/details/106048313

https://www.cnblogs.com/liuxinyustu/articles/14228934.html

本文作者欲戴王冠,必承其重...易波葉平本文連結:https://www.cnblogs.com/UncleZhao/p/14314270.html

19
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • k8s之ConfigMap