码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-16 17:24:10      阅读:374      评论:0      收藏:0      [点我收藏+]

标签:主机不可达   subprocess   queue   zabbix trapper   

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

    通过简单的ping命令判断主机是否可达。脚本基于Python3.3.6,Python2.x版本的queue模块应该是Queue。

#!/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)


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

标签:主机不可达   subprocess   queue   zabbix trapper   

原文地址:http://blog.51cto.com/13568014/2117012

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!