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. Mysql--表注释,字段注释

    information_schema数据库是MySQL数据库自带的数据库,里面存放的MySQL数据库所有的信息,包括数据表.数据注释.数据表的索引.数据库的权限等等. 1.添加表.字段注释 creat ...

  2. Educational Round 95 (Div. 2) A - B题题解(A题数据连错3次,搞人心态中)

    1418A. Buying Torches 这次A题,真心fo了(导致wa了我两次) 样例出错两次,数据出错一次. 讲一下我的思路吧. 首先先明确至少需要多少个棍.\(k\) 个火炬,至少需要$k ∗ ...

  3. 【驱动】SPI驱动分析(一)-SPI协议简介

    1. 什么是SPI SPI全拼Serial Peripheral interface(串行外围设备接口),是由Motorola(摩托罗拉)在MC68HCXX系列处理器上定义的,主要应用于EEPROM( ...

  4. C#设计模式11——享元模式的写法

    1. 什么是享元模式? 享元模式是一种结构型设计模式,目的是通过共享对象来尽量减少内存使用和对象数量.它通过将对象分为可共享的和不可共享的来实现这一目的. 2. 为什么要使用享元模式? 使用享元模式可 ...

  5. 银行个人住房贷款LPR办理流程-建行app

    8月底之前即将需完成银行的个人住房贷款定价基准利率的转换.选择"LPR+浮动利率"或者"固定利率". 以下举例建行app上办理方法给大家参考下. 办理方案: 一 ...

  6. SNMP 使用总结

    转载请注明出处: 1.SNMP简介 SNMP(Simple Network Management Protocol,简单网络管理协议)是一种用于网络设备和系统的管理协议.它允许网络管理员监控和管理网络 ...

  7. 【PID】初学者的pid,详细的介绍了代码为什么是这样写的

    from:Improving the Beginner's PID – Introduction « Project Blog (brettbeauregard.com)

  8. 【SHELL】在指定格式的文件中查找字符串

    在指定格式的文件中查找字符串 grep -nr "string" --include=*.{c,cpp,h} 在排除指定格式的文件中查找字符串 grep -nr "str ...

  9. MoeCTF 2023(西电CTF新生赛)WP

    个人排名 签到 hello CTFer 1.题目描述: [非西电] 同学注意: 欢迎你来到MoeCTF 2023,祝你玩的开心! 请收下我们送给你的第一份礼物: https://cyberchef.o ...

  10. [转帖]Oracle中INITRANS和MAXTRANS参数

    每个块都有一个块首部.这个块首部中有一个事务表.事务表中会建立一些条目来描述哪些事务将块上的哪些行/元素锁定.这个事务表的初始大小由对象的INITRANS 设置指定.对于表,这个值默认为2(索引的IN ...