本文转载自:http://blog.mreald.com/178

Zabbix可以通过自发现添加主机,不过有时候不准确,通过API添加会更加准确!

脚本使用的跟zabbix相关的内容.参考的是zabbix2.2版本的手册

Excel 格式:(列名从前到后使用空格分割)

hostname visible  hostip  dnsname proxy hostgroup hosttemp  hosttemp1

#!/usr/local/bin/python
#coding:utf-8 import json
import urllib2
from urllib2 import URLError
import sys
import xlrd class ZabbixTools:
def __init__(self):
self.url = 'http://10.10.147.183/api_jsonrpc.php'
self.header = {"Content-Type":"application/json"} def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "admin",
"password": "zabbix"
},
"id": 0
}) request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
except URLError as e:
print "Auth Failed, please Check your name and password:", e.code
else:
response = json.loads(result.read())
result.close()
self.authID = response['result']
return self.authID def host_get(self,hostName):
data = json.dumps({
"jsonrpc":"2.0",
"method":"host.get",
"params":{
"output":["hostid","name"],
"filter":{"host":hostName}
},
"auth":self.user_login(),
"id":1,
}) request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
except URLError as e:
if hasattr(e, 'reason'):
print 'We failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'The server could not fulfill the request.'
print 'Error code: ', e.code
else:
response = json.loads(result.read())
result.close()
print "Number Of %s: " % hostName, len(response['result'])
lens=len(response['result'])
if lens > 0:
return response['result'][0]['name']
else:
return "" def hostgroup_get(self, hostgroupName):
data = json.dumps({
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params":{
"output": "extend",
"filter": {
"name": [
hostgroupName,
]
}
},
"auth":self.user_login(),
"id":1,
}) request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close() lens=len(response['result'])
if lens > 0:
self.hostgroupID = response['result'][0]['groupid']
return response['result'][0]['groupid']
else:
print "no GroupGet result"
return "" def template_get(self, templateName):
data = json.dumps({
"jsonrpc":"2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"host": [
templateName,
]
}
},
"auth":self.user_login(),
"id":1,
}) request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
self.templateID = response['result'][0]['templateid']
return response['result'][0]['templateid'] def host_create(self, hostName,visibleName,hostIp,dnsName,proxyName, hostgroupName, templateName1, templateName2):
data = json.dumps({
"jsonrpc":"2.0",
"method":"host.create",
"params":{
"host": hostName,
"name": visibleName,
"proxy_hostid": self.proxy_get(proxyName),
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": hostIp,
"dns": dnsName,
"port": ""
}
],
"groups": [
{
"groupid": self.hostgroup_get(hostgroupName)
}
],
"templates": [
{
"templateid": self.template_get(templateName1) },
{ "templateid": self.template_get(templateName2)
}
],
},
"auth": self.user_login(),
"id":1
})
request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "host : %s is created! id is %s\n" % (hostip, response['result']['hostids'][0])
self.hostid = response['result']['hostids']
return response['result']['hostids'] def proxy_get(self, ProxyName):
data = json.dumps({
"jsonrpc":"2.0",
"method": "proxy.get",
"params": {
"output": "extend",
"selectInterface": "extend",
"filter": {
"host": [ ProxyName, ]
}
},
"auth":self.user_login(),
"id":1,
}) request = urllib2.Request(self.url, data)
for key in self.header:
request.add_header(key, self.header[key]) try:
result = urllib2.urlopen(request)
except URLError as e:
print "Error as ", e
else:
response = json.loads(result.read())
result.close()
self.templateID = response['result'][0]['proxyid']
return response['result'][0]['proxyid'] if __name__ == "__main__": test = ZabbixTools() workbook = xlrd.open_workbook('test.xlsx')
for row in xrange(workbook.sheets()[0].nrows):
hostname=workbook.sheets()[0].cell(row,0).value
visible=workbook.sheets()[0].cell(row,1).value
hostip=workbook.sheets()[0].cell(row,2).value
dnsname=workbook.sheets()[0].cell(row,3).value
proxy=workbook.sheets()[0].cell(row,4).value
hostgroup=workbook.sheets()[0].cell(row,5).value
hosttemp=workbook.sheets()[0].cell(row,6).value
hosttemp1=workbook.sheets()[0].cell(row,7).value hostgroup=hostgroup.strip() hostnameGet=test.host_get(hostname)
if hostnameGet.strip()=='':
test.host_create(hostname,visible,hostip,dnsname,proxy,hostgroup,hosttemp,hosttemp1)
else:
print "%s have exist! Cannot recreate !\n" % hostnameGet

  

Python调用zabbix API批量添加主机 (读取Excel)的更多相关文章

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

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

  2. python 调用zabbix api实现查询主机信息,输出所有主机ip

    之前发现搜索出来的主机调用zabbix api信息都不是那么明确,后来通过zabbix官方文档,查到想要的api信息,随后写一篇自己这次项目中用到的api. #!/usr/bin/env python ...

  3. 关于python调用zabbix api接口

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

  4. 『Python』Python 调用 ZoomEye API 批量获取目标网站IP

    #### 20160712 更新 原API的访问方式是以 HTTP 的方式访问的,根据官网最新文档,现在已经修改成 HTTPS 方式,测试可以正常使用API了. 0x 00 前言 ZoomEye 的 ...

  5. 使用Python调用Zabbix API

    Zabbix API官方文档: https://www.zabbix.com/documentation/4.0/zh/manual/api 1.向 api_jsonrpc.php 发送HTTP_PO ...

  6. python 通过zabbix api获得所有主机的ip

    #!/usr/bin/env python3 #coding=utf-8 import jsonimport requests#from urllib import requests, parse,e ...

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

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

  8. 03: zabbix API接口 对 主机、主机组、模板、应用集、监控项、触发器等增删改查

    目录:Django其他篇 01: 安装zabbix server 02:zabbix-agent安装配置 及 web界面管理 03: zabbix API接口 对 主机.主机组.模板.应用集.监控项. ...

  9. 分布式监控系统Zabbix--完整安装记录-批量添加主机和自动发现端口

    一.Zabbix-3.0.3批量添加主机的配置如下: 0)被监控机上要安装zabbix_agent,并配置好zabbix_agentd.conf (如下172.29.8.50是zabbix_serve ...

随机推荐

  1. 【堆】bzoj1293 [SCOI2009]生日礼物

    考虑poj3320尺取法的做法,与此题基本一样,但是此题的 位置 的范围到2^31 尺取法不可. 将每种珠子所在的位置排序. 每种珠子要维护一个指针,指到已经用到这个种类的哪个珠子. 所以尺取法用堆优 ...

  2. 【可持久化Trie】bzoj3261 最大异或和

    对原序列取前缀异或值,变成pre[1...N],然后询问等价于求max{a[N]^x^pre[i]}(l-1<=i<=r-1). #include<cstdio> #defin ...

  3. Scala零基础教学【41-60】

    第41讲:List继承体系实现内幕和方法操作源码揭秘 def main(args: Array[String]) { /** * List继承体系实现内幕和方法操作源码揭秘 * * List本身是一个 ...

  4. iOS 自定义相机带拍摄区域边框及半透明遮罩层(含源码)

    开始时准备封装成ViewController的相机,但是在不改我相机控件源码的情况下,使用者很难自定义UI.于是想到将相机核心功能封装到View里,暴露出功能方法给外面调用,调用者只需将LFCamer ...

  5. Centos7.4 建站系统和软件版本搭配

    一.系统和软件版本搭配 版本: 1.1.2 类型: 建站系统 适用于: Centos7.4 64bit 集成软件版本: nginx_versi=1.12.2 PHP=7.1.13 (已提供提供Zend ...

  6. 对AOP切面的一些整理与理解

      首先上一张AOP的图示 一:几个重要的概念   1> 切面:横切关注点(跨越应用程序多个模块的功能)被模块化的特殊对象[验证切面.日志切面]   2> 通知:切面中的每个方法   3& ...

  7. Quartz与Spring的整合使用

    之前说到过Quartz的基本使用(猛戳这里看文章).在实际使用中,我们一般会将定时任务交由spring容器来管理.所以今天我们来说说Quartz与spring的整合. 咱们还是依照Quartz的三大元 ...

  8. 微信小程序 - 更改button状态

    wxml <button class='yes-orders' style='{{status_css}}' bindtap='clickExpress'> {{statusOrders} ...

  9. POJ 2392 Space Elevator(贪心+多重背包)

    POJ 2392 Space Elevator(贪心+多重背包) http://poj.org/problem?id=2392 题意: 题意:给定n种积木.每种积木都有一个高度h[i],一个数量num ...

  10. LINUX经常使用命令小整理

    系统操作: 1.重新启动机器:reboot. 2.查看某程序的进程:ps -ef|grep xxx(比如:ps -ef|grep tomcat). 3.查看当前linux系统系统版本号:lsb_rel ...