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接口的更多相关文章

  1. 关于python调用zabbix api接口

    因公司业务需要,引进了自动化运维,所用到的监控平台为zbbix3.2,最近正在学习python,计划使用python调用zabbix api接口去做些事情,如生成报表,我想最基本的是要取得zabbix ...

  2. python 调用zabbix api接口实现主机的增删改查

    python程序调用zabbix系统的api接口实现对zabbix_server端主机的增删改查,使用相关功能时候,需要打开脚本中的相关函数. 函数说明: zabbixtools()  调用zabbi ...

  3. Python 封装SNMP调用接口

    PySNMP 是一个纯粹用Python实现的SNMP,用PySNMP的最抽象的API为One-line Applications,其中有两类API:同步的和非同步的,都在模块pysnmp.entity ...

  4. python调用zabbix接口实现Action配置

    要写这篇博客其实我的内心是纠结的,老实说,我对zabbix的了解实在不多.但新公司的需求不容置疑,当我顶着有两个头大的脑袋懵懵转入运维领域时,面前摆着两百多组.上千台机器等着写入zabbix监控的需求 ...

  5. python使用zabbix的API接口

    一.实验环境 python3.6.6 zabbix 3.0.9 二.实验目的 了解Zabbix的API接口格式 通过python实现登陆zabbix服务,获得登陆token 通过python检索zab ...

  6. python面向对象进阶 反射 单例模式 以及python实现类似java接口功能

    本篇将详细介绍Python 类的成员.成员修饰符.类的特殊成员. 类的成员 类的成员可以分为三大类:字段.方法和特性. 注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存 ...

  7. 转载:python + requests实现的接口自动化框架详细教程

    转自https://my.oschina.net/u/3041656/blog/820023 摘要: python + requests实现的接口自动化框架详细教程 前段时间由于公司测试方向的转型,由 ...

  8. Python人工智能之初识接口

    本节需要的两个工具: 1.FFmpeg: 链接:https://pan.baidu.com/s/1jonSAa_TG2XuaJEy3iTmHg 密码:w6hk 2.baidu-aip: pip ins ...

  9. python + requests实现的接口自动化框架详细教程

    前段时间由于公司测试方向的转型,由原来的web页面功能测试转变成接口测试,之前大多都是手工进行,利用postman和jmeter进行的接口测试,后来,组内有人讲原先web自动化的测试框架移驾成接口的自 ...

  10. python调用C语言接口

    python调用C语言接口 注:本文所有示例介绍基于linux平台 在底层开发中,一般是使用C或者C++,但是有时候为了开发效率或者在写测试脚本的时候,会经常使用到python,所以这就涉及到一个问题 ...

随机推荐

  1. 【JAVA基础】批处理脚本

    update ifp_project set is_self_run = 'N' where is_self_run is null; update ifp_invoice_header set is ...

  2. WCF 动态调用 动态代理

    关键词:WCF动态调用.动态调用WCF.WCF使用动态代理精简代码架构.使用反射执行WCF接口 代码地址: https://gitee.com/s0611163/DynamicWCF https:// ...

  3. 26-IP调用 - PLL

    1.PLL IP核简介 PLL(Phaze Locked Loop)锁相环是最常用的IP核之一,其性能强大,可以对输入到FPGA的时钟信号进行任意的分频.倍频.相位调整.占空比调整,从而输出一个期望时 ...

  4. 2023年江苏“领航杯”MISC一个很有意思的题目(别把鸡蛋放在同一个篮子里面)

    别把鸡蛋放在同一个篮子里面 题目附件:https://wwzl.lanzoue.com/i6HmX16finnc 1.题目信息 解压压缩包打开附件,获得5141个txt文档,每个文档都有内容,发现是b ...

  5. Python Code_04InputFunction

    代码部分 # coding:utf-8 # author : 写bug的盼盼 # development time : 2021/8/28 6:55 present = input('你想要什么?') ...

  6. 百度网盘(百度云)SVIP超级会员共享账号每日更新(2023.11.17)

    一.百度网盘SVIP超级会员共享账号 可能很多人不懂这个共享账号是什么意思,小编在这里给大家做一下解答. 我们多知道百度网盘很大的用处就是类似U盘,不同的人把文件上传到百度网盘,别人可以直接下载,避免 ...

  7. [转帖]MYSQL--表分区、查看分区

    https://www.cnblogs.com/pejsidney/p/10074980.html 一.       mysql分区简介 数据库分区 数据库分区是一种物理数据库设计技术.虽然分区技术可 ...

  8. [转帖]br备份时排除某个库

    https://tidb.net/blog/2a88149e?utm_source=tidb-community&utm_medium=referral&utm_campaign=re ...

  9. [转帖]K8S 挂载 minio csi 的方式.

    对象存储   前置条件 安装Minio(在102主机上操作) 安装csi-s3插件(在103主机上操作) 使用 参考 本文介绍kubernetes如何基于对象存储(minio)创建PV与PVC 前置条 ...

  10. [转帖]第5章 WINDOWS PE/COFF

    https://www.jianshu.com/p/35db9df2514f?utm_campaign=maleskine&utm_content=note&utm_medium=se ...