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. Vue3--使用脚手架创建一个vue应用,实现todolist

    一.安装脚手架,运行项目 1.1 安装,运行 首先安装 16.0 或更高版本的 Node.js 然后在cmd安装并执行 create-vue 它是 Vue 官方的项目脚手架工具 npm init vu ...

  2. 查看公网出口ip

    curl cip.cc curl http://members.3322.org/dyndns/getip curl icanhazip.com curl ident.me curl ifconfig ...

  3. Google C++编程规范(Google C++ Style Guide)

    参考链接: Google 代码规范 C++总结 Google 开源项目风格指南--中文版 Google C++ Style Guide是一份不错的C++编码指南,我制作了一张比较全面的说明图,可以在短 ...

  4. AtCoder Beginner Contest 217 D~E

    比赛链接:Here ABC水题, D - Cutting Woods 题意:开始一根木棒长度为 \(n\) 并以 \(1\) 为单位在木棒上标记\((1\sim n)\) ,输出 \(q\) 次操作 ...

  5. VIM 入门手册, (VS Code)

    要想在VScode里使用Vim需要先行按照插件 安装 vim 插件 VS Code 中输入快捷键 shift + ctrl + x, 或直接打开 扩展安装导航 搜索 vim, 选择 Vim , 点击 ...

  6. ​iOS Class Guard github用法、工作原理和安装详解及使用经验总结

    ​iOS Class Guard github用法.工作原理和安装详解及使用经验总结 iOS Class Guard是一个用于OC类.协议.属性和方法名混淆的命令行工具.它是class-dump的扩展 ...

  7. 你真的了解MySQL日期函数吗?

    MySQL提供了丰富的日期和时间函数,用于处理和操作日期时间数据.本篇博文将深入介绍一些常用的MySQL日期函数,通过详细的例子带你了解这些函数的用法和实际应用. 1. CURDATE() - 获取当 ...

  8. freeswitch新增模块APP

    概述 之前的文章中,我们讲解了freeswitch的源码基本结构,如何新增一个插件式模块,以及如何在模块中新增一个命令式API接口. freeswitch的架构非常适合这种业务开发模式,即以frees ...

  9. 04 Tcl字符串

    Tcl字符串 4.1 Tcl将说有的变量值视作字符串,并将他们作为字符串进行保存. 命令 描述 append 将值追加到字符串尾 binary 二进制化字符串 format 字符串格式化 regexp ...

  10. 关于编写C时的调试--VS,VSCODE,DEV-C++

    1.问题 VS最大的问题是不支持scanf函数,后面的调试部分我就没试了,主要用VS来写C++ VSCODE是服了他的C/C++插件,我死活卡在debug中scanf的输入部分,集成终端根本无法输入, ...