zabbix監控日誌檔案
阿新 • • 發佈:2018-11-03
需求說明
監控/opt/a.log日誌檔案,並讓其出現Error的時候就報警
操作環境
zabbix客戶端和服務端都配置完成並可以正常使用,傳送報警郵件配置配好
如何搭建zabbix環境和配置和服務端請戳這裡——> 部署zabbix
如何配置報警郵件戳——> 本地使用者傳送報警郵件 指令碼傳送報警郵件
操作步驟
- 客戶端
①.寫一個監控日誌的指令碼並修改許可權
[[email protected] ~]# vim log.py
#!/usr/bin/env python3
import sys
import re
def prePos(seekfile):
global curpos
try:
cf = open(seekfile)
except IOError:
curpos = 0
return curpos
except FileNotFoundError:
curpos = 0
return curpos
else:
try:
curpos = int(cf.readline().strip())
except ValueError:
curpos = 0
cf.close()
return curpos
cf.close()
return curpos
def lastPos(filename):
with open(filename) as lfile:
if lfile.readline():
lfile.seek(0,2)
else:
return 0
lastPos = lfile.tell()
return lastPos
def getSeekFile():
try:
seekfile = sys.argv[2]
except IndexError:
seekfile = '/tmp/logseek'
return seekfile
def getKey():
try:
tagKey = str(sys.argv[3])
except IndexError:
tagKey = 'Error'
return tagKey
def getResult(filename,seekfile,tagkey):
destPos = prePos(seekfile)
curPos = lastPos(filename)
if curPos < destPos:
curpos = 0
try:
f = open(filename)
except IOError:
print('Could not open file: %s' % filename)
except FileNotFoundError:
print('Could not open file: %s' % filename)
else:
f.seek(destPos)
while curPos != 0 and f.tell() < curPos:
rresult = f.readline().strip()
global result
if re.search(tagkey, rresult):
result = 1
break
else:
result = 0
with open(seekfile,'w') as sf:
sf.write(str(curPos))
finally:
f.close()
return result
if __name__ == "__main__":
result = 0
curpos = 0
tagkey = getKey()
seekfile = getSeekFile()
result = getResult(sys.argv[1],seekfile,tagkey)
print(result)
[ [email protected] ~]# chmod +x /scripts/log.py
②.建立存放指令碼的目錄,並修改配置檔案裡面指令碼的位置
[[email protected] ~]# mkdir /scripts/ [[email protected] ~]# chown -R zabbix.zabbix /scripts [[email protected] ~]# cp log.py /scripts/ [[email protected] ~]# vim /etc/zabbix/zabbix_agentd.conf UnsafeUserParameters=1 //修改為1 UserParameter=check_log,/usr/bin/python /scripts/log.py /opt/a.log /opt/logseek Error //第一個引數代表要監控的日誌檔案 //第二個引數代表每次檢視完日誌檔案快取看到哪裡了的日誌檔案 //第三個引數代表監控的關鍵字
③.修改/opt/的目錄許可權
[[email protected] ~]# chown zabbix.zabbix /opt/
④.在服務端測試一下指令碼
[[email protected] ~]# zabbix_get -s 172.16.11.12 -k check_log
0
- web介面
建立監控項
新增觸發器
新增動作
到這就配置完成可以測試了
- 客戶端
①.在a.log裡面新增內容,先不新增關鍵字,我們會發現記錄檢視到哪裡的檔案沒有變化,監控沒有報警
[[email protected] ~]# cat >> a.log << EOF
> error
> a
> b
> c
> EOF
[[email protected] ~]# cat /opt/logseek
0[[email protected] ~]#
②.新增關鍵字內容,可以發現檢視到哪裡的日誌檔案有變化,監控也報警了,郵件也傳送了
[[email protected] ~]# echo 'Error' >> /opt/a.log
[[email protected] ~]# cat /opt/logseek
6[[email protected] ~]#