美文网首页
使用Python调用Zabbix API获取SESSIONID

使用Python调用Zabbix API获取SESSIONID

作者: 一个小运维 | 来源:发表于2022-06-25 06:00 被阅读0次

    Zabbix API 的使用流程
    使用 API 的基本步骤
    连接 http://x.x.x.x/api_jsonrpc.php 提供用户名和密码,
    并标识 HTTP 头部 Content-Type:application/json,HTTP 方法为 POST。
    获取 SESSIONID
    通过 SESSIONID 建立后续的连接
    提交 POST 数据,格式为 JSON,其中放对应的方法,获取需要的数据。

    获取 SESSIONID
    [root@linux ~]#curl -s -X POST -H 'Content-Type:application/json' -d '
    {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": "Admin",
            "password": "zabbix"
        },
        "id": 1
    }' http://192.168.8.1/api_jsonrpc.php | python -m json.tool
    {
        "id": 1,
        "jsonrpc": "2.0",
        "result": "2ba2efb0df040e9591f94ee522fd0f45"
    }
    
    [root@linux ~]#curl -s -X POST -H 'Content-Type:application/json' -d '
    {
         "jsonrpc": "2.0",
         "method": "host.get",
         "params": {
             "output": ["hostid"]
         },
         "auth": "2ba2efb0df040e9591f94ee522fd0f45",
         "id": 1
    }' http://192.168.8.1/api_jsonrpc.php | python -m json.tool
    {
        "id": 1,
        "jsonrpc": "2.0",
        "result": [
            {
                "hostid": "10084"
            }
        ]
    }
    
    使用Python 获取用于认证获取 SESSIONID
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    
    import requests
    import json
    
    url = 'http://192.168.8.1/api_jsonrpc.php'
    post_data = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "user": "Admin",
            "password": "zabbix"
        },
        "id": 1
    }
    post_header = {'Content-Type': 'application/json'}
    
    ret = requests.post(url, data=json.dumps(post_data), headers=post_header)
    
    zabbix_ret = json.loads(ret.text)
    if 'result' not in zabbix_ret:
      print ('login error')
    else:
      print (zabbix_ret.get('result'))
    

    相关文章

      网友评论

          本文标题:使用Python调用Zabbix API获取SESSIONID

          本文链接:https://www.haomeiwen.com/subject/esxivrtx.html