python3调用zabbix api接口对自动发现添加的主机修改主机名

Posted 非淡泊无以明志

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3调用zabbix api接口对自动发现添加的主机修改主机名相关的知识,希望对你有一定的参考价值。

# _*_ coding:utf-8 _*_
import json
import requests

#zabbix服务器的IP地址
zabbix_ip = "XXX"
#zabbix的用户名
zabbix_user = "XXX"
#zabbix的密码
zabbix_pass = "XXX"
#zabbix api接口地址
url = "http://" + zabbix_ip + ":80/zabbix/api_jsonrpc.php"
#zabbix api定义的访问头部信息
post_header = {Content-Type: application/json}



# 调用zabbix api需要身份令牌auth
def get_auth():
    post_data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": zabbix_user,
            "password": zabbix_pass
        },
        "id": "1"
    }

    ret = requests.post(url, data=json.dumps(post_data), headers=post_header)
    zabbix_ret = json.loads(ret.text)
    print(zabbix_ret)
    if result not in zabbix_ret:
        print(login error)
    else:
        auth = zabbix_ret.get(result)
        return auth


# 以IP信息获取主机id
def get_hostid():
    hostid_get = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": "extend",
            "filter": {
                "host": [
                    host_ip
                ]
            }
        },
        "auth": Token,
        "id": 2,
    }

    res2 = requests.post(url, data=json.dumps(hostid_get), headers=post_header)
    res3 = res2.json()
    #print(res3)
    res4 = res3[result]
    host_id = res4[0][hostid]
    return host_id

# 以主机ID来修改主机名
def update_hostname():
    hostname_update = {
        "jsonrpc": "2.0",
        "method": "host.update",
        "params": {
            "hostid": host_id,
            "name": host_name
        },
        "auth": Token,
        "id": 3
    }

    res10 = requests.post(url, data=json.dumps(hostname_update), headers=post_header)
    res11 = res10.json()
    #print(res11)

if __name__ == __main__:
    ‘‘‘
    ips.txt里的文件内容:
    主机名1 ip1
    主机名2 ip2
    主机名3 ip3
    ‘‘‘
    with open("ips.txt", "r", encoding="utf8") as f:
        for line in f:
            line = line.split(" ")
            host_name = line[0] + "."
            host_ip = line[1].strip()
            #print(host_name)
            #print(host_ip)

            Token = get_auth()
            #print(Token)
            host_id = get_hostid()
            #print(host_id)
            update_hostname()
            print(host_name,host_ip,"已添加完成")

 

以上是关于python3调用zabbix api接口对自动发现添加的主机修改主机名的主要内容,如果未能解决你的问题,请参考以下文章

利用python3 调用zabbix接口完成批量加聚合图形(screens)

调用微信API发送微信消息python脚本

通过API自动增加Zabbix监控主机

Zabbix3.0 API调用

调用zabbix的api接口导出主机配置信息

调用zabbix API获取主机