zabbix python add host py

简介: 没有该主机组的时候要先添加主机组:./python_zabbix_host.py -A yournamevi python_zabbix_host.py!/usr/bin/pythoncoding:utf-8import jsonimport...

没有该主机组的时候要先添加主机组:./python_zabbix_host.py -A yourname

vi python_zabbix_host.py

!/usr/bin/python

coding:utf-8

import json
import urllib2
from urllib2 import URLError
import sys, argparse
import xlrd
import socket
import os

os.chdir('/usr/local/src')
os.system('yum install -y unzip')
if os.path.exists('setuptools-38.2.4') == False:
os.system(
'wget https://pypi.python.org/packages/69/56/f0f52281b5175e3d9ca8623dadbc3b684e66350ea9e0006736194b265e99/setuptools-38.2.4.zip#md5=e8e05d4f8162c9341e1089c80f742f64 --no-check-certificate')
os.system('unzip setuptools-38.2.4.zip')
os.chdir('/usr/local/src/setuptools-38.2.4')
os.system('python setup.py build')
os.system('python setup.py install')
os.chdir('/usr/local/src')
if os.path.exists('pip-9.0.1') == False:
os.system(
'wget --no-check-certificate https://pypi.python.org/packages/11/b6/abcb525026a4be042b486df43905d6893fb04f05aac21c32c638e939e447/pip-9.0.1.tar.gz#md5=35f01da33009719497f01a4ba69d63c9')
os.system('tar -xzvf pip-9.0.1.tar.gz')
os.chdir('/usr/local/src/pip-9.0.1')
os.system('python setup.py build')
os.system('python setup.py install')
os.system('pip install xlrd')
else:
os.chdir('/usr/local/src/pip-9.0.1')
os.system('pip install xlrd')

defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)

def get_host_ip():
"""
查询本机ip地址
:return: ip
"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()

return ip

a = get_host_ip()

class zabbix_api:
def init(self):
self.url = 'http://' + a + '/zabbix/api_jsonrpc.php' # 修改URL
self.header = {"Content-Type": "application/json"}

def user_login(self):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": "admin",  # web页面登录用户名
            "password": "zabbix"  # web页面登录密码
        },
        "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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code
    else:
        response = json.loads(result.read())
        result.close()
        # print response['result']
        self.authID = response['result']
        return self.authID

def host_get(self, hostName=''):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": "extend",
            "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())
        # print response
        result.close()
        print "主机数量: \033[31m%s\033[0m" % (len(response['result']))
        for host in response['result']:
            status = {"0": "OK", "1": "Disabled"}
            available = {"0": "Unknown", "1": "available", "2": "Unavailable"}
            # print host
            if len(hostName) == 0:
                print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m" % (
                host['hostid'], host['name'], status[host['status']], available[host['available']])
            else:
                print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m" % (
                host['hostid'], host['name'], status[host['status']], available[host['available']])
                return host['hostid']

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:
        # print result.read()
        response = json.loads(result.read())
        result.close()
        # print response()
        for group in response['result']:
            if len(hostgroupName) == 0:
                print "hostgroup:  \033[31m%s\033[0m \tgroupid : %s" % (group['name'], group['groupid'])
            else:
                print "hostgroup:  \033[31m%s\033[0m\tgroupid : %s" % (group['name'], group['groupid'])
                self.hostgroupID = group['groupid']
                return group['groupid']

def template_get(self, templateName=''):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": "extend",
            "filter": {
                "name": 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()
        # print response
        for template in response['result']:
            if len(templateName) == 0:
                print "template : \033[31m%s\033[0m\t  id : %s" % (template['name'], template['templateid'])
            else:
                self.templateID = response['result'][0]['templateid']
                print "Template Name :  \033[31m%s\033[0m " % templateName
                return response['result'][0]['templateid']

def hostgroup_create(self, hostgroupName):

    if self.hostgroup_get(hostgroupName):
        print "hostgroup  \033[42m%s\033[0m is exist !" % hostgroupName
        sys.exit(1)
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "hostgroup.create",
        "params": {
            "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()
        print "\033[042m 添加主机组:%s\033[0m  hostgroupID : %s" % (hostgroupName, response['result']['groupids'])

def host_create_andy(self, hostName, visibleName, hostip, hostgroupName, templateName):
    if self.host_get(hostip):
        print "\033[041m该主机已经添加!\033[0m"
        sys.exit(1)

    group_list = []
    template_list = []
    for i in hostgroupName.split(','):
        var = {}
        var['groupid'] = self.hostgroup_get(i)
        group_list.append(var)
    for i in templateName.split(','):
        var = {}
        var['templateid'] = self.template_get(i)
        template_list.append(var)

    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostName,
            "name": visibleName,
            "interfaces": [
                {
                    "type": 1,  # 1:表示IP;2表示SNMP
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": "10050"  # IP端口10050;SNMP端口161
                }
            ],
            "groups": group_list,
            "templates": template_list,
        },
        "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())
        print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
        result.close()

def host_create(self, hostip, hostgroupName, templateName):
    if self.host_get(hostip):
        print "\033[041m该主机已经添加!\033[0m"
        sys.exit(1)

    group_list = []
    template_list = []
    for i in hostgroupName.split(','):
        var = {}
        var['groupid'] = self.hostgroup_get(i)
        group_list.append(var)
    for i in templateName.split(','):
        var = {}
        var['templateid'] = self.template_get(i)
        template_list.append(var)

    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": hostip,
            "interfaces": [
                {
                    "type": 2,
                    "main": 1,
                    "useip": 1,
                    "ip": hostip,
                    "dns": "",
                    "port": "161"
                }
            ],
            "groups": group_list,
            "templates": template_list,
        },
        "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 "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])

def host_disable(self, hostip):
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.update",
        "params": {
            "hostid": self.host_get(hostip),
            "status": 1
        },
        "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 '----主机现在状态------------'
        print self.host_get(hostip)

def host_delete(self, hostid):
    hostid_list = []
    # print type(hostid)
    for i in hostid.split(','):
        var = {}
        var['hostid'] = self.host_get(i)
        hostid_list.append(var)
    data = json.dumps({
        "jsonrpc": "2.0",
        "method": "host.delete",
        "params": hostid_list,
        "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 Exception, e:
        print  e
    else:

        result.close()
        print "主机 \033[041m %s\033[0m  已经删除 !" % hostid

if name == "main":
zabbix = zabbix_api()
parser = argparse.ArgumentParser(description='zabbix api ', usage='%(prog)s [options]')
parser.add_argument('-H', '--host', nargs='?', dest='listhost', default='host', help='查询主机')
parser.add_argument('-G', '--group', nargs='?', dest='listgroup', default='group', help='查询主机组')
parser.add_argument('-T', '--template', nargs='?', dest='listtemp', default='template', help='查询模板信息')
parser.add_argument('-A', '--add-group', nargs=1, dest='addgroup', help='添加主机组')
parser.add_argument('-C', '--add-host', dest='addhost', nargs=3,
metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'), help='添加主机,多个主机组或模板使用分号')
parser.add_argument('-d', '--disable', dest='disablehost', nargs=1, metavar=('192.168.2.1'), help='禁用主机')
parser.add_argument('-L', '--allin', dest='allin', nargs='?', default='allin', help='从Excel批量导入主机')
parser.add_argument('-D', '--delete', dest='deletehost', nargs='+', metavar=('192.168.2.1'), help='删除主机,多个主机之间用分号')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 1.0')
if len(sys.argv) == 1:
print parser.print_help()
else:
args = parser.parse_args()

    if args.listhost != 'host':
        if args.listhost:
            zabbix.host_get(args.listhost)
        else:
            zabbix.host_get()
    if args.listgroup != 'group':
        if args.listgroup:
            zabbix.hostgroup_get(args.listgroup)
        else:
            zabbix.hostgroup_get()
    if args.listtemp != 'template':
        if args.listtemp:
            zabbix.template_get(args.listtemp)
        else:
            zabbix.template_get()
    if args.addgroup:
        zabbix.hostgroup_create(args.addgroup[0])
    if args.addhost:
        zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
    if args.disablehost:
        zabbix.host_disable(args.disablehost)
    if args.deletehost:
        zabbix.host_delete(args.deletehost[0])
    if args.allin != 'allin':
        workbook = xlrd.open_workbook('zabbix_host_add.xlsx')  # Excel名,表格列 主机名、显示名、IP、主机组、模板
        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
            hostgroup = workbook.sheets()[0].cell(row, 3).value
            hosttemp = workbook.sheets()[0].cell(row, 4).value

            zabbix.host_create_andy(hostname, visible, hostip, hostgroup, hosttemp)
目录
相关文章
|
JSON 监控 前端开发
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
python对接API二次开发高级实战案例解析:Zabbix API封装类实现获取认证密钥、所有主机组、所有主机、所有监控项和历史数据
502 0
|
5天前
|
开发者 Python
Python中__init__.py文件的作用
`__init__.py`文件在Python包管理中扮演着重要角色,通过标识目录为包、初始化包、控制导入行为、支持递归包结构以及定义包的命名空间,`__init__.py`文件为组织和管理Python代码提供了强大支持。理解并正确使用 `__init__.py`文件,可以帮助开发者更好地组织代码,提高代码的可维护性和可读性。
10 2
|
4月前
|
IDE 开发工具 Python
【Python】已完美解决:SyntaxError: Non-UTF-8 code starting with ‘æ‘ in file E:/Python/3.py on line 4, but no
【Python】已完美解决:SyntaxError: Non-UTF-8 code starting with ‘æ‘ in file E:/Python/3.py on line 4, but no
137 0
|
2月前
|
Python Windows
Python:执行py命令,提示: Can‘t find a default Python.
Python:执行py命令,提示: Can‘t find a default Python.
|
3月前
|
Ubuntu Linux 数据安全/隐私保护
使用Cython库包对python的py文件(源码)进行加密,把python的.py文件生成.so文件并调用
本文介绍了在Linux系统(Ubuntu 18.04)下将Python源代码(`.py文件`)加密为`.so文件`的方法。首先安装必要的工具如`python3-dev`、`gcc`和`Cython`。然后通过`setup.py`脚本使用Cython将`.py文件`转化为`.so文件`,从而实现源代码的加密保护。文中详细描述了从编写源代码到生成及调用`.so文件`的具体步骤。此方法相较于转化为`.pyc文件`提供了更高的安全性。
121 2
|
3月前
|
移动开发 Java 编译器
什么是pyc文件,把python的py文件编译成pyc文件,把pyc文件反编译成py文件。以及python编译的如何设置不生成pyc文件
什么是pyc文件,把python的py文件编译成pyc文件,把pyc文件反编译成py文件。以及python编译的如何设置不生成pyc文件
48 1
|
4月前
|
安全 Python
【Python】已完美解决:WARNING: The repository located at mirrors .aliyun.com is not a trusted or secure host
【Python】已完美解决:WARNING: The repository located at mirrors .aliyun.com is not a trusted or secure host
246 1
|
6月前
|
Python
Python 的其他主题:Python 中的 `__init__.py` 文件有什么作用?
Python 的其他主题:Python 中的 `__init__.py` 文件有什么作用?
73 1
|
4月前
|
监控 Python
【Python】已解决:requests.exceptions.ConnectTimeout: HTTPConnectionPool(host=‘123.96.1.95’, port=30090)
【Python】已解决:requests.exceptions.ConnectTimeout: HTTPConnectionPool(host=‘123.96.1.95’, port=30090)
196 0
|
4月前
|
安全 网络协议 网络安全
【Python】已解决:pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool (host=’ files. pyth
【Python】已解决:pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool (host=’ files. pyth
359 0
下一篇
无影云桌面