从Python脚本判断服务器不可达,到Zabbix报警
1、Python脚本获取不可达服务器的IP:脚本基于Python3.3.6,Python2.x版本的queue模块应该是Queue,导入模块时:"from Queue import Queue"。
通过简单的ping命令判断主机是否可达。脚本会读取/etc/zabbix/scripts/iplist.txt文件中的内容,文件中每个IP占用一行,允许有“#”开头的注释行内容。
#!/usr/bin/python
#-*- coding: utf-8 -*-
from __future__ import print_function
import re
import subprocess
import threading
from queue import Queue
from queue import Empty
def is_reachable(ip):
'''根据ping命令的返回值,判断IP是否可以ping通。如果返回值不是0,说明不通,输出该IP'''
if subprocess.getstatusoutput('ping -c 1 {0}'.format(ip)) != 0:
print(ip,end=',')
def unreachable_ip(ip_queue):
'''不用等待,从IP队列中取出IP,调用is_reachable函数,直到队列中的内容为空'''
try:
while True:
ip = ip_queue.get_nowait()
is_reachable(ip)
except Empty:
pass
def get_unreachable_ip(filename, ip_queue, threads):
'''从iplist文件中获取IP,加入到队列中。创建5个线程调用unreachable_ip函数'''
with open(filename, 'rt') as fin:
for line in fin:
if line and not re.match('#', line):
ip_queue.put(line.split('\n'))
for i in range(5):
thr = threading.Thread(target=unreachable_ip, args=(ip_queue,))
thr.start()
threads.append(thr)
for thr in threads:
thr.join()
if __name__ == '__main__':
filename = '/etc/zabbix/scripts/iplist.txt'
ip_queue = Queue()
threads = []
get_unreachable_ip(filename, ip_queue, threads) 2、Zabbix报警:
已经可以通过脚本获取到不可达主机的IP,怎样让Zabbix获取这些IP呢?
如果使用Zabbix的zabbix agent模式获取的话,因为ping不可达的IP时,返回内容会有延迟,这样可能会因为Zabbix执行脚本超时导致item不可用。我使用zabbix trapper向zabbix server发送数据。
[*] 首先创建item,需要注意的是“Type of information”,如果选择“Numeric”会报类似于“value not supported”的错误。item设置如下图:
http://s1.运维网.com/images/20180516/1526460558781222.png
[*] 使用zabbix_sender命令向zabbix server发送数据:
选项:
-s --host host:指定主机名,IP和DNS不可用。agent的配置文件中定义或者zabbix的web页面上。以下命令中,因为直接在zabbix server上执行的脚本,所以-s使用了“Zabbix server”;
-z --zabbix-server server:zabbix server的主机名或IP地址;
-k --key key:item中的key;
-o --value value:item中key的value,这里使用脚本的结果作为value。value不支持多行内容,所以在脚本is_reachable函数中,将print结束符指定为“,”。
# /usr/local/zabbix/bin/zabbix_sender -s "Zabbix server" -z 127.0.0.1 -k "ip_unreachable" -o `/etc/zabbix/scripts/test_ping_new.py`
info from server: "processed: 1; failed: 0; total: 1; seconds spent: 0.000038"
sent: 1; skipped: 0; total: 1
[*] 设定一个定时任务,每隔几分钟执行一次zabbix_sender命令,向zabbix server发送数据。
[*] 设置触发器:
设置触发器表达式(Expression),我选择“No date received during period of time T”,时间为5分钟,初始值是“0”,如下图:
http://s1.运维网.com/images/20180516/1526462731332227.png
可以在Trigger的Name中通过{ITEM.VALUE}获取item的值,Trigger设置如下图:
http://s1.运维网.com/images/20180516/1526462406280109.png
下图是测试时,收到的一条报警短信:
http://s1.运维网.com/images/20180516/1526464582102747.jpg
3、对比:
下面是很久之前写的一个shell脚本,循环ping主机,因为是一个IP完成之后,再去ping下一个IP,循环效率很低:
#!/bin/bash
while true
do
i=0
ip_array=()
for IP in $(cat /etc/zabbix/scripts/login_iplist.txt | grep -v "^#")
do
KEY=$(ping $IP -c 5 | grep "ttl" | wc -l)
if [ $KEY -eq 0 ]
then
ip_array[$i]=$IP
i=$(( $i + 1 ))
fi
done
if [ ${#ip_array[@]} -ne 0 ]
then
/usr/local/zabbix/bin/zabbix_sender -s "Zabbix server" -z 127.0.0.1 -k "test_ping" -o "${ip_array
[*]} unreachable"
fi
done
页:
[1]