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. .net 温故知新【17】:Asp.Net Core WebAPI 中间件

    一.前言 到这篇文章为止,关于.NET "温故知新"系列的基础知识就完结了,从这一系列的系统回顾和再学习,对于.NET core.ASP.NET CORE又有了一个新的认识. 不光 ...

  2. kafka集群五、__consumer_offsets副本数修改

    系列导航 一.kafka搭建-单机版 二.kafka搭建-集群搭建 三.kafka集群增加密码验证 四.kafka集群权限增加ACL 五.kafka集群__consumer_offsets副本数修改 ...

  3. <vue 基础知识 8、购物车样例>

    代码结构 一.     效果 1. 展示列表v-for 2. 购买数量增加减少,使用@click触发回调函数. 减少的时候如果已经为1了就不让继续减少,使用了v-bind绑定属性 3. 移除也是使用@ ...

  4. 【译】 双向流传输和ASP.NET Core 3.0上的gRPC简介

    原文相关 原文作者:Eduard Los 原文地址:https://medium.com/@eddyf1xxxer/bi-directional-streaming-and-introduction- ...

  5. java实现微信扫码登录功能 精讲

    java实现微信扫码登录功能 精讲 https://www.bilibili.com/video/BV1RJ411N7ne?from=search&seid=18091761082032798 ...

  6. freeswitch-1.10.7性能测试

    概述 freeswitch 是一款简单好用的开源软交换平台. freeswitch-1.10.7是比较新的版本,使用时间比较短,需要一个可参考的性能指标,作为实际使用过程中的配置指导. 环境 cent ...

  7. C#将汉字转换为拼音

    首先上效果图 方法调用 private void txt_Chinese_TextChanged(object sender, EventArgs e) { txt_PinYIn.Text = //调 ...

  8. Liunx常用操作(八)-sed命令详细说明

    一.sed简介 sed是一种流编编器,它是文本处理中非常中的工具,能够完美的配合正则表达式便用,功物能不同凡响. 处理时,把当前处理的行存储在临时缓冲区中,称为"模式空间"( oa ...

  9. spring启动流程 (4) FactoryBean详解

    FactoryBean接口 实现类对象将被用作创建Bean实例的工厂,即调用getObject()方法返回的对象才是真正要使用的Bean实例,而不是直接将FactoryBean对象作为暴露的Bean实 ...

  10. [转帖]linux中top性能分析工具中的TIME+

    top命令的TIME/TIME+是指的进程所使用的CPU时间,不是进程启动到现在的时间,因此,如果一个进程使用的cpu很少,那即使这个进程已经存在N长时间,TIME/TIME+也是很小的数值. 此外, ...