调用zabbix 相关api 进行批量操作

import json
import requests
import pymysql as mysql

mysql_conn= mysql.connect(
    host = "127.0.0.1",
    port = 3306,
    user = "root",
    passwd = "123456",
    db = "poll",
    charset="utf8"
)

url = "http://1.1.1.1/zabbix/api_jsonrpc.php"
header = {"Content-Type": "application/json"}


##获取api 令牌,在第一次请求的时候需要获取到令牌才能访问
# data = json.dumps(
#     {
#         "jsonrpc": "2.0",
#         "method": "user.login",
#         "params": {
#             "user": "Admin",
#             "password": "123456"
#         },
#         "id": 1,
#
#     }
# )
#
# request = requests.post(url, data=data, headers=header)
# print(request.text)

### 获取想要操作的组的groupID:

# data1 = json.dumps({
#     "jsonrpc": "2.0",
#     "method": "hostgroup.get",
#     "params": {
#         "output": "groupid",
#         "filter": {
#             "name": [
#                 "123456"
#             ]
#         }
#     },
#     "auth": "123456",
#     "id": 1
# })
# request1 = requests.post(url, data=data1, headers=header)
# b = json.loads(request1.text)['result']
# print(b)

##获取groupid 为57的组得 机器信息

# data_host = json.dumps(
#     {
#         "jsonrpc": "2.0",
#         "method": "host.get",
#         "params": {
#             "output": ["hostid"],
#             "selectInterfaces": [ "ip" ],
#             "groupids": "57",
#             "available": "1",
#         },
#         "auth": "123456",
#         "id": 1
#     }
# )
# request_host = requests.post(url, data = data_host, headers=header)
# b = json.loads(request_host.text)['result']
# j = jsonpath.jsonpath(b, '$..hostid')
# print(b)





##修改主机名为ip-应用名 这种形式
def update_hostname(filename):
    file = open(filename)
    str = "-"
    for i in file.readlines():
        ip = i.split(' ')[0]
        name = i.split(' ')[1]
        sql = '''SELECT hostid FROM `poll`.`hosts` WHERE `host` = '%s' LIMIT 0,1000;''' %ip
        rcursor = mysql_conn.cursor()
        rcursor.execute(sql)
        id = rcursor.fetchone()
        seq = (ip,name)
        try:
            update_host = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "host.update",
                    "params": {
                        "hostid": id[0],
                        "name": str.join( seq ),
                    },
                "auth": "08d4797699d636ca732e22bd759ea189",
                "id": 1
            }
            )
            request_update_host = requests.post(url, data=update_host, headers=header)
            sc = json.loads(request_update_host.text)
            print(sc)

        except Exception as e:
            print(e)
    file.close()
    rcursor.close()


##修改宏
def update__usermacro(filename):
    file = open(filename)
    for f in file.readlines():
        k = f.split(' ')[0]
        v = f.split(' ')[1].strip('\n').strip()
        w = v.strip('\n').strip()
        sql = '''SELECT hostid FROM `poll`.`hosts` WHERE `host` = '%s' LIMIT 0,1000;''' % k
        rcursor = mysql_conn.cursor()
        rcursor.execute(sql)
        id = rcursor.fetchone()
        sql1 = '''SELECT hostmacroid FROM `poll`.`hostmacro` WHERE `hostid` = '%s' AND `macro` = '{$APP_NAME}' LIMIT 0,1000;''' %id[0]
        rcursor = mysql_conn.cursor()
        rcursor.execute(sql1)
        macroid = rcursor.fetchone()
        try:

            update_macro = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "usermacro.update",
                    "params": {
                        "hostmacroid": macroid[0],
                        "macro": "{$APP_NAME}",
                        "value": w
                    },
                    "auth": "123456",
                    "id": 1
                }
            )
            request_update_macro = requests.post(url, data=update_macro, headers=header)
            sc = json.loads(request_update_macro.text)
            print(sc)
        except Exception as e:
            print(e)

    file.close()
    rcursor.close()


def delete_usermacro(filename):
    file = open(filename)
    for f in file.readlines():
        k = f.split(' ')[0]
        v = f.split(' ')[1].strip()
        sql = '''SELECT hostid FROM `poll`.`hosts` WHERE `host` = '%s' LIMIT 0,1000;''' % k
        rcursor = mysql_conn.cursor()
        rcursor.execute(sql)
        id = rcursor.fetchone()
        # print(id[0])
        try:
            update_macro = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "usermacro.delete",
                    "params": {
                        "hostid": id[0],
                        "macro": "{$APP_NAME}",
                        "value": v
                    },
                    "auth": "123456",
                    "id": 1
                }
            )
            request_update_macro = requests.post(url, data=update_macro, headers=header)
            sc = json.loads(request_update_macro.text)
            print(sc)
        except Exception as e:
            print(e)


##批量打开监控项
def open_items(filename, item):
    file = open(filename)
    for f in file.readlines():
        k = f.split(' ')[0]
        sql = '''SELECT hostid FROM `poll`.`hosts` WHERE `host` = '%s' LIMIT 0,1000;''' % k
        rcursor = mysql_conn.cursor()
        rcursor.execute(sql)
        id = rcursor.fetchone()
        sql1 = '''SELECT itemid FROM `poll`.`items` WHERE `hostid` = '%s' AND `name` = '%s' LIMIT 0,1000;''' %(id[0], item)

        rcursor.execute(sql1)
        itemid = rcursor.fetchone()


        try:

            update_macro = json.dumps(
                {
                    "jsonrpc": "2.0",
                    "method": "item.update",
                    "params": {
                        "itemid": itemid[0],
                        "status": "0"

                    },
                    "auth": "123456",
                    "id": 1
                }
            )
            request_update_macro = requests.post(url, data=update_macro, headers=header)
            sc = json.loads(request_update_macro.text)
            print(sc)
        except Exception as e:
            print(e)

    file.close()
    rcursor.close()








if __name__ == '__main__':
#     #create_usermacro('hosts')
#
#     #update_hostname('host-new')
     #update__usermacro('hosts')
    open_items('hosts', 'Port 8080 Status')
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容