Python封装zabbix-get接口的代码分享

Zabbix 是一款强大的开源网管监控工具,该工具的客户端与服务端是分开的,我们可以直接使用自带的zabbix_get命令来实现拉取客户端上的各种数据,在本地组装参数并使用Popen开子线程执行该命令,即可实现批量监测。

封装Engine类: 该类的主要封装了Zabbix接口的调用,包括最基本的参数收集.

import subprocess,datetime,time,math

class Engine():
    def __init__(self,address,port):
        self.address = address
        self.port = port

    def GetValue(self,key):
        try:
            command = "get.exe -s {0} -p {1} -k {2}".format(self.address,self.port,key).split(" ")
            start = datetime.datetime.now()
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            while process.poll() is None:
                time.sleep(1)
                now = datetime.datetime.now()
                if (now - start).seconds > 2:
                    return 0
            return str(process.stdout.readlines()[0].split()[0],"utf-8")
        except Exception:
            return 0

    # ping检测
    def GetPing(self):
        ref_dict = {"Address":0,"Ping":0}
        ref_dict["Address"] = self.address
        ref_dict["Ping"] = self.GetValue("agent.ping")
        if ref_dict["Ping"] == "1":
            return ref_dict
        else:
            ref_dict["Ping"] = "0"
            return ref_dict
        return ref_dict

    # 获取主机组基本信息
    def GetSystem(self):
        ref_dict = { "Address" : 0 ,"HostName" : 0,"Uname":0 }
        ref_dict["Address"] = self.address
        ref_dict["HostName"] = self.GetValue("system.hostname")
        ref_dict["Uname"] = self.GetValue("system.uname")
        return ref_dict

    # 获取CPU利用率
    def GetCPU(self):
        ref_dict = { "Address": 0 ,"Core": 0,"Active":0 , "Avg1": 0 ,"Avg5":0 , "Avg15":0 }
        ref_dict["Address"] = self.address
        ref_dict["Core"] = self.GetValue("system.cpu.num")
        ref_dict["Active"] = math.ceil(float(self.GetValue("system.cpu.util")))
        ref_dict["Avg1"] = self.GetValue("system.cpu.load[,avg1]")
        ref_dict["Avg5"] = self.GetValue("system.cpu.load[,avg5]")
        ref_dict["Avg15"] = self.GetValue("system.cpu.load[,avg15]")
        return ref_dict

    # 获取内存利用率
    def GetMemory(self):
        ref_dict = { "Address":"0","Total":"0","Free":0,"Percentage":"0" }
        ref_dict["Address"] = self.address

        fps = self.GetPing()
        if fps['Ping'] != "0":
            ref_dict["Total"] = self.GetValue("vm.memory.size[total]")
            ref_dict["Free"] = self.GetValue("vm.memory.size[free]")
            # 计算百分比: percentage = 100 - int(Free/int(Total/100))
            ref_dict["Percentage"] = str( 100 - int( int(ref_dict.get("Free")) / (int(ref_dict.get("Total"))/100)) ) + "%"
            return ref_dict
        else:
            return ref_dict

    # 获取磁盘数据
    def GetDisk(self):
        ref_list = []

        fps = self.GetPing()
        if fps['Ping'] != "0":
            disk_ = eval( self.GetValue("vfs.fs.discovery"))
            for x in range(len(disk_)):
                dict_ = {"Address": 0, "Name": 0, "Type": 0, "Free": 0}
                dict_["Address"] = self.address
                dict_["Name"] = disk_[x].get("{#FSNAME}")
                dict_["Type"] = disk_[x].get("{#FSTYPE}")
                if dict_["Type"] != "UNKNOWN":
                    pfree = self.GetValue("vfs.fs.size[\"{0}\",pfree]".format(dict_["Name"]))
                    dict_["Free"] = str(math.ceil(float(pfree)))
                else:
                    dict_["Free"] = -1
                ref_list.append(dict_)
            return ref_list
        return ref_list

    # 获取进程状态
    def GetProcessStatus(self,process_name):
        fps = self.GetPing()
        dict_ = {"Address": '0', "ProcessName": '0', "ProcessCount": '0', "Status": '0'}
        if fps['Ping'] != "0":
            proc_id = self.GetValue("proc.num[\"{}\"]".format(process_name))
            dict_['Address'] = self.address
            dict_['ProcessName'] = process_name
            if proc_id != "0":
                dict_['ProcessCount'] = proc_id
                dict_['Status'] = "True"
            else:
                dict_['Status'] = "False"
            return dict_
        return dict_

    # 获取端口开放状态
    def GetNetworkPort(self,port):
        dict_ = {"Address": '0', "Status": 'False'}
        dict_['Address'] = self.address
        fps = self.GetPing()
        if fps['Ping'] != "0":
            port_ = self.GetValue("net.tcp.listen[{}]".format(port))
            if port_ == "1":
                dict_['Status'] = "True"
            else:
                dict_['Status'] = "False"
            return dict_
        return dict_

    # 检测Web服务器状态 通过本地地址:端口 => 检测目标地址:端口
    def CheckWebServerStatus(self,check_addr,check_port):
        dict_ = {"local_address": "0", "remote_address": "0", "remote_port": "0", "Status":"False"}
        fps = self.GetPing()
        dict_['local_address'] = self.address
        dict_['remote_address'] = check_addr
        dict_['remote_port'] = check_port
        if fps['Ping'] != "0":
            check_ = self.GetValue("net.tcp.port[\"{}\",\"{}\"]".format(check_addr,check_port))
            if check_ == "1":
                dict_['Status'] = "True"
            else:
                dict_['Status'] = "False"
            return dict_
        return dict_

当我们需要使用时,只需要定义变量调用即可,其调用代码如下。

from engine import Engine

if __name__ == "__main__":
    ptr_windows = Engine("127.0.0.1","10050")
    ret = ptr_windows.GetDisk()
    if len(ret) != 0:
        for item in ret:
            addr = item.get("Address")
            name = item.get("Name")
            type = item.get("Type")
            space = item.get("Free")
            if type != "UNKNOWN" and space != -1:
                print("地址: {} --> 盘符: {} --> 格式: {} --> 剩余空间: {}".format(addr,name,type,space))

到此这篇关于Python封装zabbix-get接口的代码分享的文章就介绍到这了,更多相关Python封装zabbix-get接口内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • zabbix利用python脚本发送报警邮件的方法

    前言 zabbix是个非常强大的监控工具,可以监控linux和windows的服务器数据,也可以通过自定义key来扩展默认的监控项,但是自带的邮件报警提供的信息却不太友善.本文想通过自定脚本的方式,实现在报警邮件的同时发送对应的图像和url连接. 步骤如下: 1.编辑zabbix_server.conf文件,修改AlertScriptsPath参数,该参数用于指定外部脚本的绝对路径. vim /etc/zabbix/zabbix_server.conf AlertScriptsPath=/usr

  • python通过zabbix api获取主机

    zabbix强大地方在于有强大的api,zabbix 的api可以拿到zabbix大部分数据,目前我所需的数据基本可以通过api获取,以下是通过zabbix api获取的主机信息python代码,其他数据也如此类推,api使用方法可参见官网文档: #!/usr/bin/env python #-*- coding: utf-8 -*- import json import urllib2 from urllib2 import URLError from login import zabbix_

  • python实现zabbix发送短信脚本

    本文实例为大家分享了zabbix发送短信的具体代码,供大家参考,具体内容如下 使用方法 ./sendSMS.py PHONE_NUMBER args_2 SMS_MSG 接收参数输入 参数一: 接收手机号(zabbix传来的第1个参数,报警接收手机号),第一个参数可以对比发送邮件的脚本 参数二: 短信主题(zabbix传来的第2个参数,报警主题),在命令行测试必须输入,用来占位,脚本中并不获取这个参数 参数三: 短信内容(zabbix传来的第3个参数,报警内容) 手动调试方法 python se

  • python实现Zabbix-API监控

    做运维的朋友应该知道,公司IDC机房经常有上架.下架.报修和报废的服务器.如果服务器数量很多的时候很容易造成监控遗漏. 大的互联网公司把监控系统和CMDB(资产管理系统|配置管理数据库系统)集成在一起,当上架一台新机器的时候CMDB里面会记录相关的信息,Zabbix根据CMDB里面信息自动Link相关的模块,添加|删除监控.很多小的公司没有资产管理系统,但作为监控的负责人应该每天知道上架了哪些新的机器,确保能添加到Zabbix监控里面. 首先给大家说一下脚本思路: 1)通过Nmap工具扫描网段,

  • python3实现zabbix告警推送钉钉的示例

    自己写了一个简单的python脚本,用来推送zabbix告警到钉钉机器人,推送格式为markdown,有需要的可以自己修改markdown的格式及推送的值(zabbix宏) 环境如下,理论上zabbix版本不影响,可以看看官方宏定义是否有区别 python 3 zabbix 3.4.2 zabbix宏官方文档:https://www.zabbix.com/documentation/3.4/manual/appendix/macros/supported_by_location 配置 配置钉钉自

  • Python 调用 zabbix api的方法示例

    前提准备: 1.使用python requests模块 2.了解json 3.zabbix api的具体调用建议先浏览一下官网 先上代码: import requests,json # #url一定要正确,IP地址换成自己zabbix服务器的 zbx_url = "http://192.168.60.130:3080/zabbix/api_jsonrpc.php" #在post请求头部必须要有 'Content-Type': 'application/json-rpc' headers

  • Python封装zabbix-get接口的代码分享

    Zabbix 是一款强大的开源网管监控工具,该工具的客户端与服务端是分开的,我们可以直接使用自带的zabbix_get命令来实现拉取客户端上的各种数据,在本地组装参数并使用Popen开子线程执行该命令,即可实现批量监测. 封装Engine类: 该类的主要封装了Zabbix接口的调用,包括最基本的参数收集. import subprocess,datetime,time,math class Engine(): def __init__(self,address,port): self.addre

  • Python封装SNMP调用接口的示例代码

    PySNMP 是一个纯粹用Python实现的SNMP,用PySNMP的最抽象的API为One-line Applications,其中有两类API:同步的和非同步的,都在模块pysnmp.entity.rfc3413.oneliner.cmdgen 中实现,如下是Get方式与Walk方式的基本实现. 首先需要在系统中安装SNMP客户端,对于Linux平台来说只需要执行如下配置过程即可. [root@localhost ~]# yum install -y net-snmp [root@local

  • Python的净值数据接口调用示例分享

    代码描述:基于Python的净值数据接口调用代码实例 关联数据:净值数据 接口地址:https://www.juhe.cn/docs/api/id/25 #!/usr/bin/python # -*- coding: utf-8 -*- import json, urllib from urllib import urlencode #---------------------------------- # 净值数据调用示例代码 - 聚合数据 # 在线接口文档:http://www.juhe.c

  • 在Python web中实现验证码图片代码分享

    系统版本: CentOS 7.4 Python版本: Python 3.6.1 在现在的WEB中,为了防止爬虫类程序提交表单,图片验证码是最常见也是最简单的应对方法之一. 1.验证码图片的生成   在python中,图片验证码一般用PIL或者Pillow库实现,下面就是利用Pillow生成图片验证码的代码: #!/usr/bin/env python3 #- * -coding: utf - 8 - * -#@Author: Yang#@ Time: 2017 / 11 / 06 1: 04 i

  • python绘制铅球的运行轨迹代码分享

    我们按照面向过程程序设计的思想,使用python编写了程序,追踪铅球在运行过程中的位置信息.下面,修改程序代码,导入turtle模块,将铅球的运行轨迹绘制出来. python3代码如下: from math import pi, sin, cos, radians from turtle import Turtle def main(): angle = eval(input('Enter the launch angle(in degrees):')) vel = eval(input('En

  • Python numpy生成矩阵、串联矩阵代码分享

    import numpy 生成numpy矩阵的几个相关函数: numpy.array() numpy.zeros() numpy.ones() numpy.eye() 串联生成numpy矩阵的几个相关函数: numpy.array() numpy.row_stack() numpy.column_stack() numpy.reshape() >>> import numpy >>> numpy.eye(3) array([[ 1., 0., 0.], [ 0., 1.

  • Python中pygal绘制雷达图代码分享

    pygal的安装和简介,大家可以参阅<pip和pygal的安装实例教程>,下面看看通过pygal实现绘制雷达图代码示例. 雷达图(Radar): import pygal radar_chart = pygal.Radar() radar_chart.title = 'V8 benchmark results' radar_chart.x_labels = ['Richards', 'DeltaBlue', 'Crypto', 'RayTrace', 'EarleyBoyer', 'RegEx

  • Python学习pygal绘制线图代码分享

    pygal的安装大家可以参阅:pip和pygal的安装实例教程 线图: import pygal line_chart = pygal.Line() line_chart.title = 'Browser usage evolution (in %)' line_chart.x_labels = map(str, range(2002, 2013)) line_chart.add('Firefox', [None, None, 0, 16.6, 25, 31, 36.4, 45.5, 46.3,

  • python将数据插入数据库的代码分享

    python将数据插入数据库的方法: 首先读入数据并建立数据库连接: 然后创建数据库: 接着执行插入数据语句,迭代读取每行数据: 最后关闭数据库连接即可. 比如现在我们要将如下Excel数据表格插入到MySQL数据库中,该如何实现呢? 实现代码: #导入需要使用到的数据模块 import pandas as pd import pymysql #读入数据 filepath = 'E:\_DataSet\catering_sale.xls' data = pd.read_excel(filepat

  • 利用Python实现绘制3D爱心的代码分享

    目录 环境介绍 第一步,绘制一个三维的爱心 亿点点细节 加入时间序列 加入心脏的跳动 一个好的展示 完整代码 环境介绍 python3.8 numpy matplotlib 第一步,绘制一个三维的爱心 关于这一步,我采用的是大佬博客中的最后一种绘制方法.当然,根据我的代码习惯,我还是稍做了一点点修改的. class Guess: def __init__(self, bbox=(-1.5, 1.5), resolution=50, lines=20) -> None: ""&qu

随机推荐