zabbix Python3管理
import requests
import json
import os # user config here
ip = '192.168.52.130'
user = "root"
password = "123" # user config end
class ZabbixApi:
def __init__(self, ip, user, password):
self.url = 'http://' + ip + '/api_jsonrpc.php'
self.headers = {"Content-Type": "application/json",
}
self.user = user
self.password = password
self.auth = self.__login() def __login(self):
'''
zabbix登陆获取auth
:return: auth # 样例bdc64373690ab9660982e0bafe1967dd
'''
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.user,
"password": self.password
},
"id": 1,
})
try:
response = requests.post(url=self.url, headers=self.headers, data=data, timeout=2)
# {"jsonrpc":"2.0","result":"bdc64373690ab9660982e0bafe1967dd","id":10}
auth = response.json().get('result', '')
return auth
except Exception as e:
print("\033[0;31;0m Login error check: IP,USER,PASSWORD\033[0m")
raise Exception def host_get(self, hostname=''):
'''
获取主机。不输入hostname 则获取所有
:param hostName: zabbix主机名不允许重复。(IP允许重复)。#host_get(hostname='gateway1')
:return: {'jsonrpc': '2.0', 'result': [], 'id': 21}
:return: {'jsonrpc': '2.0', 'result': [{'hostid': '10277', ... , 'host': 'gateway', ...}], 'id': 21}
'''
if hostname == '':
print("no hostname and find all host")
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 1,
"auth": self.auth
})
else:
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {"output": "extend",
"filter": {"host": hostname},
},
"id": 1,
"auth": self.auth
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
return response.json() # len(ret.get('result'))为1时获取到,否则未获取到。
except Exception as e:
print("\033[0;31;0m HOST GET ERROR\033[0m")
raise Exception def get_items(self, hostid='', host=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "item.get",
"params": {
"output": ["itemids", host],
"hostids": hostid,
},
"auth": self.auth, # theauth id is what auth script returns, remeber it is string
"id": 1,
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get('result',''))
return response.json() # len(ret.get('result'))为1时获取到,否则未获取到。 except Exception as e:
print("\033[0;31;0m Template GET ERROR\033[0m")
raise Exception def get_history(self,itemid=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "history.get",
"params": {
"output": "extend",
"history": 3,
"itemids": itemid,
"sortfield": "clock",
"sortorder": "DESC",
"limit": 10 },
"auth": self.auth,
"id": 1
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get('result',''))
return response.json() # len(ret.get('result'))为1时获取到,否则未获取到。 except Exception as e:
print("\033[0;31;0m Template GET ERROR\033[0m")
raise Exception def hostgroup_create(self, hostGroupName=''):
if len(self.hostgroup_get(hostGroupName).get('result')) == 1:
print("无需创建,hostgroup存在")
return 100
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostGroupName
},
"auth": self.auth,
"id": 1
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get('result',''))
# print('l',hosts)
return response.json() # len(ret.get('result'))为1时获取到,否则未获取到。 except Exception as e:
print("\033[0;31;0m HOSTGROUP CREATE ERROR\033[0m")
raise Exception def template_get(self, templateName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"name": templateName
}
},
"auth": self.auth,
"id": 50,
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get('result',''))
# print('l',hosts)
return response.json() # len(ret.get('result'))为1时获取到,否则未获取到。 except Exception as e:
print("\033[0;31;0m Template GET ERROR\033[0m")
raise Exception def host_create(self, hostname, hostip, hostGroupName, templateName):
'''
创建host,并分配分组,关联模版
host_create('host3','1.1.1.1','gp1 test,gp2 test','Template App FTP Service,Template App HTTP Service')
:param hostname: 'host3'
:param hostip: '1.1.1.1'
:param hostGroupName: 多个组逗号分割'gp1 test,gp2 test'
:param templateName: 多个模版都逗号分割'Template App FTP Service,Template App HTTP Service'
:return:
'''
# 判断主机名是否重复。 zabbix不允许主机名重复
find_hostname = self.host_get(hostname)
if len(find_hostname.get('result')):
print("###recheck### hostname[%s] exists and return" % hostname)
return 1 # 判断template是否存才,不存在退出。 否则初始化备用
template_list = []
for t in templateName.split(','):
find_template = self.template_get(t)
if not len(find_template.get('result')):
# template不存在退出 # 一般因为输错关系
print("###recheck### template[%s] not find and return " % t)
return 1 tid = self.template_get(t).get('result')[0]['templateid']
template_list.append({'templateid': tid}) # 判断hostgroup是否存在。 不存在则创建。 并初始化hostgroup_list备用
hostgroup_list = []
for g in hostGroupName.split(','):
find_hostgroupname = self.hostgroup_get(g)
if not len(find_hostgroupname.get('result')):
# hostgroupname 不存在,创建
self.hostgroup_create(g)
# {'jsonrpc': '2.0', 'result': [{'groupid': '15', 'name': 'linux group 1', 'internal': '0', 'flags': '0'}],'id': 1} # for g in hostGroupName.split(','):
# print(self.hostgroup_get(g).get('result'))
gid = self.hostgroup_get(g).get('result')[0]['groupid']
hostgroup_list.append({'groupid': gid}) # print("## 测试组信息 ##")
# print(hostgroup_list)
# print(template_list) data = json.dumps({
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": hostname,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": hostip,
"dns": "",
"port": "10050"
}
],
"groups": hostgroup_list,
"templates": template_list,
},
"auth": self.auth,
"id": 1
}) try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get('result',''))
# print('l',hosts)
print("执行返回信息: 添加HOST[%s,%s]完成" % (hostname, hostip))
return response.json() # len(ret.get('result'))为1时获取到,否则未获取到。 except Exception as e:
print("\033[0;31;0m HOST CREATE ERROR\033[0m")
raise Exception def hostgroup_get(self, hostGroupName=''):
'''
获取主机组
:param hostGroupName:
:return: {'jsonrpc': '2.0', 'result': [{'groupid': '15', 'name': 'linux group 1', 'internal': '0', 'flags': '0'}], 'id': 1}
'''
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": hostGroupName
}
},
"auth": self.auth,
"id": 1,
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get('result',''))
# print('l',hosts)
return response.json() # len(ret.get('result'))为1时获取到,否则未获取到。 except Exception as e:
print("\033[0;31;0m HOSTGROUP GET ERROR\033[0m")
raise Exception zabbix = ZabbixApi(ip, user, password)
hostinfo = zabbix.host_get("XuYiJi")
hostid = hostinfo.get("result")[0].get("hostid")
host = hostinfo.get("result")[0].get("host")
items = zabbix.get_items(hostid, host)
itemid = items.get("result")[0].get("itemid")
history = zabbix.get_history(itemid)
stat = history.get("result")[0].get("value")
clock = history.get("result")[0].get("clock")
print("hostid:","\033[0;37;40m{}\033[0m".format(hostid))
print("host:","\033[0;37;40m{}\033[0m".format(host))
print("itemid:","\033[0;37;40m{}\033[0m".format(itemid))
print("stat:","\033[0;37;40m{}\033[0m".format(stat))
import time, datetime
timeStamp = int(clock)
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) print("clock:","\033[0;37;40m{}\033[0m".format(otherStyleTime)) # 获取/创建hostgroup测试
# groupinfo=zabbix.hostgroup_get('Linux servers')
# print(groupinfo)
# r=zabbix.hostgroup_create(hostGroupName='gt3')
# print(r)
# 获取template测试
# r=zabbix.template_get('Template OS Linux by Prom')
# print(r)
# https://www.cnblogs.com/infaaf/p/9950004.html 参考本文档
# if __name__ == '__main__':
# try:
# zabbix = ZabbixApi(ip, user, password)
# print("...login success...")
# # unittest()
#
# # 添加主机单台
# # zabbix.host_create('host7','1.1.1.1','gp1 test,gp2 test','Template OS Linux by Prom')
#
# # 批量添加主机,从文本serverlist.txt
# BASE_DIR = os.path.dirname(os.path.abspath(__file__))
#
# ADD_LIST= os.path.join(BASE_DIR,'serverlist.txt')
# with open(ADD_LIST,'r',encoding='utf-8') as f:
# for line in f:
# if len(line.strip()): #跳过空行
# serverinfo=line.strip().split('#')
# print(serverinfo)
# print("-"*60)
# print(serverinfo[0].strip("'"),serverinfo[1].strip("'"),serverinfo[2].strip("'"),serverinfo[3].strip("'"))
# zabbix.host_create(serverinfo[0],serverinfo[1],serverinfo[2],serverinfo[3])
#
# except Exception as e:
# print(e)
zabbix Python3管理的更多相关文章
- zabbix用户管理
zabbix用户管理,主要包括用户增删改查.用户报警媒介管理.用户权限管理. 安装完zabbix后,已经自带了两个用户Admin和Guests 超级管理员默认账号:Admin,密码:zabbix,这是 ...
- Zabbix页面管理
Zabbix页面管理 Screen Screen翻译成中文为"屏幕",在一些交通管理中心.保安监控.预警中心等等地方都比较常见到监控视频,视频上有多块小视频,实际上Zabbix S ...
- (3)zabbix用户管理
登陆zabbix 默认账号:Admin,密码:zabbix,这是一个超级管理员.登陆之后在右下角可以看到“connected as Admin“(中文版:连接为Admin). zabbix组介绍 我们 ...
- zabbix web管理页面 中文乱码问题
1.在自己电脑上找下图文件,C:\Windows\Fonts 2.上传到 /usr/share/zabbix/assets/fonts/ 目录下 可以看到 graphfont.ttf 是 /etc/a ...
- Zabbix (四)用户管理
本文章主要介绍zabbix用户管理,包括用户增删改查.用户报警媒介管理.用户权限管理 安装完zabbix后,系统会自带两个用户,分别为:Admin和Guests 一.超级管理员 zabbix安装完成后 ...
- CentOS下Zabbix安装部署及汉化
搭建环境:Centos6.5_x86_64,Zabbix2.4.5,epel 源 服务端: 1.安装开发软件包yum -y groupinstall "Development Tools&q ...
- zabbix完整安装
一.nginx安装 1.必要软件准备: 为了支持rewrite功能,我们需要安装pcre: yum install pcre-* 需要ssl的支持,如果不需要ssl支持,请跳过这一步: yum ins ...
- zabbix
snmp监控服务器客户端需安装net-snmp net-snmp-utils 然后修改/etc/snmp/snmpd.conf 启动snmpd服务 自定义监控项目:需在agent端的zabbix_ag ...
- LNMP+zabbix分布式监控搭建及版本升级
LNMP+zabbix分布式监控搭建需要组件:gcc gcc-c++ openssl* pcre pcre-devel gd gd-devel libjpeg-devel libpng-devel l ...
随机推荐
- 搜索Ex (洛谷提高历练地)
搜索Ex P1120 小木棍 题意:不超过65根长度小于50的小木棍(是由一批等长木棍砍断得到的),求原始木棍的最小可能长度 分析:优化+减枝爆搜 搜索状态要记录当前尝试的已经填好的长度,当前尝试填的 ...
- Codeforces Round #648 (Div. 2) D. Solve The Maze
这题犯了一个很严重的错误,bfs 应该在入队操作的同时标记访问,而不是每次只标记取出的队首元素. 题目链接:https://codeforces.com/contest/1365/problem/D ...
- 南阳ccpc C题 The Battle of Chibi 树状数组+dp
题目: Cao Cao made up a big army and was going to invade the whole South China. Yu Zhou was worried ab ...
- AtCoder Beginner Contest 188 E - Peddler (树)
题意:有\(n\)个点,\(m\)条单向边,保证每条边的起点小于终点,每个点都有权值,找到联通的点的两个点的最大差值. 题解:因为题目说了起点小于终点,所以我们可以反向存边,然后维护连通边的前缀最小值 ...
- Educational DP Contest E - Knapsack 2 (01背包进阶版)
题意:有\(n\)个物品,第\(i\)个物品价值\(v_{i}\),体积为\(w_{i}\),你有容量为\(W\)的背包,求能放物品的最大价值. 题解:经典01背包,但是物品的最大体积给到了\(10^ ...
- 在QT C++中调用 Python并将软件打包发布(裸机可运行)
为了提高工作效率,需要一个可以自动生成多份相关联的word文档免去繁琐复制粘贴工作的软件.最后选定使用QT C++做界面和主要逻辑程序设计,对word的操作使用python写好对应的函数,然后在QT中 ...
- WOJ1024 (POJ1985+POJ2631) Exploration 树/BFS
title: WOJ1024 (POJ1985+POJ2631) Exploration 树/BFS date: 2020-03-20 10:43:00 categories: acm tags: [ ...
- Leetcode(105)-从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 前序遍历 preorder = [3,9,20,15,7] 中序遍历 inorder = [9,3,15, ...
- C# 类 (11) - Const
Const variable 变量 ,值可变的constant 常量,不可变,C# 里关键字是const当我们定义一个常量的时候,需要立马赋值,以后不能再改这个量了我们可以把常量定义在 method ...
- 牛客多校第六场G Is Today Friday?(吉姆拉尔森/蔡勒公式 + 思维)题解
题意: 给你\(A-J\)的字母组成的日期,形式为\(yyyy/mm/dd\).现给你\(n\)个这样的串\((n<=1e5)\),问你把字母映射成数字,并且使得所有日期合法且为星期五的最小字典 ...