通过Django2.0+zabbix打印监控报警值

系统环境:Linux CentOS7.3

软件版本:Django 2.0 + python3.6.4


1.创建django项目,将项目命名为zabbix_target。

python-admin startproject zabbix_target

2.创建App,并命名为moniter

python manage.py startapp moniter

3.编辑Django配置文件setting.py,添加以下内容:

#添加App项目名称
INSTALLED_APPS = [
    'moniter'
]

#关闭django安全机制
MIDDLEWARE = [
    # 'django.middleware.csrf.CsrfViewMiddleware',
]

#设置模板目录
TEMPLATES = [
    {
        'DIRS': ['templates'],
    },
]

#设置静态文件目录
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static/'),
)

4.编辑moniter目录下的views.py文件,通过zabbixAPI接口调用相关信息,并通过render渲染方法将数据发送给前端。

from django.shortcuts import render
from django.http import  HttpResponse

# Create your views here.
from pyzabbix import ZabbixAPI
import time


###pyzabbix
class pyzabbixAPI(object):
    def __init__(self):
        self.prioritytostr = {'0': 'ok', '1': '信息', '2': '警告', '3': '故障','4':'严重','5':'灾难'}  # 告警级别
    def login(self):
        '''''
        进行认证
        返回 api 接口
        '''
        zapi = ZabbixAPI('http://120.27.232.133:20000/zabbix')
        zapi.login('Admin', 'shengyan777.com')
        return zapi

    def getCurIssue(self, zapi):
        '''''
        获取所有最近有问题的trigger
        返回trigger的信息列表: ['trigger1','trigger2',......]
        '''
        triggers = zapi.trigger.get(
            only_true=1,
            skipDependent=1,
            monitored=1,
            active=1,
            output='extend',
            expandDescription=1,
            selectHosts=['host'],
        )

        # 获取未确认的trigger
        unack_triggers = zapi.trigger.get(
            only_true=1,
            skipDependent=1,
            monitored=1,
            active=1,
            output='extend',
            expandDescription=1,
            selectHosts=['host'],
            withLastEventUnacknowledged=1,
        )
        unack_trigger_ids = [t['triggerid'] for t in unack_triggers]
        for t in triggers:
            t['unacknowledged'] = True if t['triggerid'] in unack_trigger_ids else False

            # 每个trigger信息格式 :[时间] 级别:ip - 详情 是否确认
        hostlist = []
        triggerlist = []
        timelist =[]

        for t in triggers:
            if int(t['value']) == 1:
                # triggerlist.append("[{0}] {1} : {2}({3}) - {4} {5}".format(
                timelist.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(t['lastchange']))))
                hostlist.append(t['hosts'][0]['host'])
                triggerlist.append("({0})-{1}".format(
                    # time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(t['lastchange']))),
                    self.prioritytostr[t['priority']],
                    # self.getHostgroupName(zapi, t['hosts'][0]['host']),
                    t['description'],
                    # '(Unack)' if t['unacknowledged'] else ''
                )
                )
        return hostlist,triggerlist,timelist

    def getHostgroupName(self, zapi, hostname):
        '''''
        通过hostname(即ip)获取host所在的监控组名
        返回由组名组成的字符串
        '''
        groups = zapi.host.get(
            search={"name": hostname},
            selectGroups=['name'],
            output=['groups']
        )[0]['groups']
        groupname = [group['name'] for group in groups]
        return ' '.join(groupname)

def zabbix(request):
    papi = pyzabbixAPI()
    zapi = papi.login()
    Host = papi.getCurIssue(zapi)[0][::-1]
    target = papi.getCurIssue(zapi)[1][::-1] #列表倒序
    Time = papi.getCurIssue(zapi)[2][::-1]
    return render(request,'index.html',locals())

5.在templates目录下新建一个index.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Zabbix Moniter</title>
    <meta http-equiv="refresh" content="30" />
    <link rel="stylesheet" href="../static/css/style.css">
</head>
<body>
    <div class="left-div">
        <div class="title_list">ZABBIX故障列表</div>
        <div style="width: 15%;float: left">
            {% for Hostinfo in Host %}
                <div class="target_info">{{ Hostinfo }}</div>
            {% endfor %}
        </div>
        <div style="width: 65%;float: left">
            {% for i in target %}
            {% if "信息" in i %}
                <div class="target_info">{{ i }}</div>
            {% elif "警告" in i%}
                <div class="target_warning">{{ i }}</div>
            {% elif "故障" in i %}
                <div class="target_ave">{{ i }}</div>
            {% elif "严重" in i %}
                <div class="target_high">{{ i }}</div>
            {% elif "灾难" in i %}
                <div class="target_dis">{{ i }}</div>
            {% else %}
                <div class="target_ok">{{ i }}</div>
            {% endif %}
            {% endfor %}
        </div>
        <div style="width: 20%;float: left">
            {% for timeinfo in Time %}
                <div class="target_info">{{ timeinfo }}</div>
            {% endfor %}
        </div>
    </div>
<div class="right-div">
图形界面
</div>

</body>
</html>

5.在项目的根目录下新建一个static/css目录,并在css目录下新建一个style.css文件

.target_dis{
    color: black;
    background-color: #FF3838;
    font-family:inherit;
    font-size: 17px;
    height: 30px;
    margin-top: 2px;
    padding: 12px 6px;
}
.target_high{
    color: black;
    background-color: #ff9999;
    font-family:inherit;
    font-size: 17px;
    height: 30px;
    margin-top: 2px;
    padding: 12px 6px;
}
.target_ave{
    color: black;
    background-color: #FFB689;
    font-family:inherit;
    font-size: 17px;
    height: 30px;
    margin-top: 2px;
    padding: 12px 6px;
}
.target_warning{
    color: black;
    background-color: #fff6A5;
    font-family:inherit;
    font-size: 17px;
    height: 30px;
    margin-top: 2px;
    padding: 12px 6px;
}
.target_info{
    color: black;
    background-color: #D6F6FF;
    font-family:inherit;
    font-size: 17px;
    height: 30px;
    margin-top: 2px;
    padding: 12px 6px;
}
.target_ok{
    color: black;
    background-color: forestgreen;
    font-family:inherit;
    font-size: 17px;
    height: 30px;
    margin-top: 2px;
    padding: 12px 6px;
}
.target_time{
    color: black;
    background-color: #ffffff;
    font-family:inherit;
    font-size: 17px;
    height: 30px;
    margin-top: 2px;
    padding: 12px 6px;
}
.title_list{
    font-weight: 900;
    background-color: lightgray;
    font-family:inherit;
    font-size: 32px;
    margin-bottom: 2px;
    padding: 12px 6px;

}
.title_graph{
    font-weight: 900;
    background-color: lightgray;
    font-family:inherit;
    font-size: 32px;
    margin-bottom: 2px;
    padding: 12px 6px;

}
.left-div{
    float: left;
    width: 49%;
}
.right-div{
    float: right;
    width: 49%;
}

6.编辑zabbix_target目录下的urls.py文件,设置App的访问路径

from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('zabbix', views.zabbix),
]

7.执行以下命令,就可以访问打印出来的故障列表了

python manage.py runserver 8000   #默认IP127.0.0.1,设置TCP端口为8000
python manage.py runserver 192.168.0.100:8000   #设置访问IP为192.168.0.100,设置TCP端口为8000

8.在浏览器中输入http://127.0.0.1:8000/zabbix就可以访问了,效果图如下:

 

 

发表回复

Your email address will not be published.

名字 *
电子邮件 *
站点