从Python脚本判断服务器不可达,到Zabbix报警

1、Python脚本获取不可达服务器的IP:

    通过简单的ping命令判断主机是否可达。

#!/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] != 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')[0])

    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)


猜你喜欢

转载自blog.51cto.com/13568014/2117012