广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python封装zabbix-get接口的代码分享
  • 938
分享到

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

2024-04-02 19:04:59 938人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

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

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接口内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Python封装zabbix-get接口的代码分享

本文链接: https://www.lsjlt.com/news/119551.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python封装zabbix-get接口的代码分享
    Zabbix 是一款强大的开源网管监控工具,该工具的客户端与服务端是分开的,我们可以直接使用自带的zabbix_get命令来实现拉取客户端上的各种数据,在本地组装参数并使用Popen...
    99+
    2022-11-11
  • 分享四个python接口常用封装函数
    目录1.封装上传图片的函数2. 封装车牌号的函数3. 封装生成UUid 函数4. 封装连接数据库的函数前言: 又到每日分享Python小技巧的时光了,今天给大家分享的是Python接...
    99+
    2022-11-10
  • Python封装SNMP调用接口的示例代码
    PySNMP 是一个纯粹用Python实现的SNMP,用PySNMP的最抽象的API为One-line Applications,其中有两类API:同步的和非同步的,都在模块pysn...
    99+
    2022-11-11
  • Python接口自动化之request请求封装源码分析
    目录1. 源码分析2. requests请求封装3. 总结前言: 我们在做自动化测试的时候,大家都是希望自己写的代码越简洁越好,代码重复量越少越好。那么,我们可以考虑将request...
    99+
    2022-11-11
  • node.js实现微信JS-API封装接口的示例代码
    Wechat JS-API接口 功能: 用于管理和获取微信 JSSDK 生产的access_token、jsapi_ticket和签名(signature) Installation npm i we...
    99+
    2022-06-04
    示例 接口 代码
  • Java编程接口调用的作用及代码分享
    很多JAVA初级程序员对于接口存在的意义很疑惑。不知道接口到底是有什么作用,为什么要定义接口。好像定义接口是提前做了个多余的工作。下面我给大家总结了4点关于JAVA中接口存在的意义:  1、重要性:在Java语言中, abstract cl...
    99+
    2023-05-30
    java 接口
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作