本文转载自: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. 10.1(java学习笔记)JDBC基本操作(连接,执行SQL语句,获取结果集)

    一.JDBC JDBC的全称是java database connection java数据库连接. 在java中需要对数据库进行一系列的操作,这时就需要使用JDBC. sun公司制定了关于数据库操作 ...

  2. 金融应用,计算酬金 Exercise06_11

    /** * @author 冰樱梦 * 时间:2018年下半年 * 题目:金融应用,计算酬金 * */ public class Exercise06_11 { public static void ...

  3. java读写文件及保留指定位小数

    1)先上代码: public static void main(String[] args)throws IOException{ double[][] B=new double[1043][2102 ...

  4. 使用shell生成随机数

    #!/bin/bash $` do $` do s=$(($RANDOM%)) done done 第1行:#!/bin/bash是指此脚本使用/bin/bash来解释执行.其中,#!是一个特殊的表示 ...

  5. Java高级架构师(一)第24节:加入ehcache,把工程加入到Git

    ehcache的maven配置: <!-- ehcache的jar --> <dependency> <groupId>net.sf.ehcache</gro ...

  6. Saga的实现模式——进化(Saga implementation patterns – variations)

    在之前的几个博客中,我主要讲了两个saga的实现模式: 基于command的控制者模式 基于事件的观察者模式 当然,这些都不是实现saga的唯一方式.我们甚至可以将这些结合起来. 发布者——收集者 回 ...

  7. JavaScript跳转到页面某个锚点#

    JavaScript跳转到页面某个锚点: scroll(0, document.getElementById('锚点ID').offsetTop);

  8. 取代Promise的Generator生成器函数

    接触过Ajax请求的会遇到过异步调用的问题,为了保证调用顺序的正确性,一般我们会在回调函数中调用,也有用到一些新的解决方案如Promise相关的技术. 在异步编程中,还有一种常用的解决方案,它就是Ge ...

  9. vb6 wininet

    Private Const UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; .NET CLR 1.1.4322)&qu ...

  10. sqlserver 获取系统用户表结构信息

    SELECT (case when a.colorder=1 then d.name else null end) 表名, a.colorder 字段序号,a.name 字段名, (case when ...