python3 call zabbix api interface automatically discovers hosts modify the host name added

# _ * _ Coding: UTF-8 _ * _ 
Import json
 Import Requests 

# zabbix server's IP address 
zabbix_ip = "XXX " 
# zabbix username 
zabbix_user = "XXX " 
# zabbix password 
zabbix_pass = "XXX " 
# zabbix API Interface address 
URL = " HTTP: // " + zabbix_ip + " : 80 / ZABBIX / api_jsonrpc.php " 
# ZABBIX API to access the header information defined 
post_header = { ' the Content-the Type ' : ' file 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 in the file content:
    Hostname 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, " has been added to complete " )

 

Guess you like

Origin www.cnblogs.com/qiufengluolei/p/11922366.html