python实现zabbix增删查

本文介绍了一个使用Python实现的Zabbix自动化运维脚本,包括登录Zabbix API、获取主机列表、主机群组信息、模板信息,以及添加和删除主机的功能。通过此脚本,可以批量管理和监控Zabbix中的主机,提高运维效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests
import json
import getpass
from random import choice

zabbix_url = 'http://192.168.200.31/api_jsonrpc.php'
zabbix_headers = {'Content-Type': 'application/json-rpc'}


def login():
    '''登录成功返回token(auth_code),登录失败返回None'''
    zabbix_user = input('username:').strip()
    zabbix_pass = getpass.getpass().strip()
    auth_data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": zabbix_user,
            "password": zabbix_pass
        },
        "id": 1
    }
    response = requests.post(zabbix_url, data=json.dumps(auth_data), headers=zabbix_headers).json()
    if "result" in response:
        print('Login successful!')
        auth_code = response["result"]
        return auth_code
    else:
        print('Login failed: ', response['error']['data'])


def get_host(auth_code):
    '''获取被控主机的信息'''
    get_host_data = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": "extend",
        },
        "auth": auth_code,
        "id": 1
    }
    response = requests.post(zabbix_url, data=json.dumps(get_host_data), headers=zabbix_headers).json()
    if 'result' in response:
        r = response['result']
        if r:
            print('%-10s%-15s%20s%20s%20s%20s%20s' % (
                'hostid', 'host', 'status', 'available', 'snmp_available', 'jmx_available', 'ipmi_available'))
            for i in range(len(r)):
                print('%-10s%-15s%20s%20s%20s%20s%20s' % (
                    r[i]['hostid'], r[i]['host'], r[i]['status'], r[i]['available'], r[i]['snmp_available'],
                    r[i]['jmx_available'], r[i]['ipmi_available']))
        else:
            print('cant not find any host')
    else:
        print('ERROR: ', response['error']['data'])


def get_hostgroup(auth_code):
    '''获取被控主机的群组信息'''
    get_hostgroup_data = {
        "jsonrpc": "2.0",
        "method": "hostgroup.get",
        "params": {
            "output": "extend",
        },
        "auth": auth_code,
        "id": 1
    }
    response = requests.post(zabbix_url, data=json.dumps(get_hostgroup_data), headers=zabbix_headers).json()
    if 'result' in response:
        r = response['result']
        if r:
            print('%-10s%-15s' % ('groupid', 'name'))
            for i in range(len(r)):
                print('%-10s%-15s' % (r[i]['groupid'], r[i]['name']))
        else:
            print('cant not find any group')
    else:
        print('ERROR: ', response['error']['data'])


def get_template(auth_code):
    '''获取被控主机的模板信息'''
    get_template_data = {
        "jsonrpc": "2.0",
        "method": "template.get",
        "params": {
            "output": "extend",
        },
        "auth": auth_code,
        "id": 1
    }
    response = requests.post(zabbix_url, data=json.dumps(get_template_data), headers=zabbix_headers).json()
    if 'result' in response:
        r = response['result']
        if r:
            print('%-20s%-15s' % ('templateid', 'name'))
            for i in range(len(r)):
                print('%-20s%-15s' % (r[i]['templateid'], r[i]['host']))
        else:
            print('can not find any template')
    else:
        print('ERROR: ', response['error']['data'])


def add_host(auth_code):
    agent_host_name = input('host name:').strip()  # 被控主机名
    agent_ip = input('ip address:').strip()  # 被控端ip地址
    groupid = input('group id(以", "分隔:')
    templateid = input('template id(以","分隔):')
    create_host = {
        "jsonrpc": "2.0",
        "method": "host.create",
        "params": {
            "host": agent_host_name,
            "interfaces": [
                {
                    "type": 1,
                    "main": 1,
                    "useip": 1,
                    "ip": agent_ip,
                    "dns": "",
                    "port": "10050"
                }
            ],
            "groups": [
                {
                    "groupid": groupid
                }
            ],
            "templates": [
                {
                    "templateid": templateid
                }
            ],
            # "inventory_mode": 0,
            # "inventory": {
            #     "macaddress_a": "01234",
            #     "macaddress_b": "56768"
            # }

        },

        "auth": auth_code,
        "id": 1
    }
    response = requests.post(zabbix_url, data=json.dumps(create_host), headers=zabbix_headers).json()
    print(response)


def del_host(auth_code):
    hostid = input("hostid(以‘,'分隔):").strip()
    delete_host = {
        "jsonrpc": "2.0",
        "method": "host.delete",
        "params": [
            hostid
        ],
        "auth": auth_code,
        "id": 1
    }
    response = requests.post(zabbix_url, data=json.dumps(delete_host), headers=zabbix_headers).json()
    print(response)


if __name__ == '__main__':

    menu = """
             welcome to zabbix
    1.host list
    2.show all groups
    3.show all templates
    4.add host
    5.delete host
    6.exit
    Please input your choice:"""
    auth_code = login()
    cmd = {'1': get_host, '2': get_hostgroup, '3': get_template, '4': add_host, '5': del_host,
           '6': exit}
    while True:
        ch = input(menu).strip()[0]
        if ch not in '1234567':
            break
        else:
            if ch == '6':
                cmd[ch]()
            else:
                cmd[ch](auth_code)
                continue

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值