Chinaunix首页 | 论坛 | 博客
  • 博客访问: 350439
  • 博文数量: 52
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 577
  • 用 户 组: 普通用户
  • 注册时间: 2013-04-27 14:21
个人简介

知道自己该干嘛,知道自己能干嘛

文章分类

全部博文(52)

文章存档

2019年(1)

2018年(8)

2017年(2)

2016年(11)

2015年(3)

2014年(10)

2013年(17)

我的朋友

分类: 系统运维

2015-07-09 14:59:24


                             最近需要收集zabbix 主机分组信息,使用API , 编写如下小脚本,代码如下:

  1. #!/usr/bin/env python2.7

  2. import json
  3. import requests


  4. def Query(username,passwd):
  5.         auth = json.dumps(
  6.                     {
  7.                         "jsonrpc": "2.0",
  8.                         "method": "user.login",
  9.                         "params": {
  10.                         "user": username,
  11.                         "password": passwd
  12.                                   },
  13.                     "id": 0
  14.                     }
  15.         )

  16.         try:
  17.                 req = requests.post(url,auth,headers=header)
  18.         except requests.exceptions.ConnectionError,e:
  19.                 print "Auth Failed, Please Check Your zabbix domain:",e
  20.         else:
  21.                 authtoken = req.json()['result']


  22.         query = json.dumps(
  23.                    {
  24.                         "jsonrpc": "2.0",
  25.                         "method": "host.get",
  26.                         "params": {
  27.                         "output": ["host"],
  28.                         "selectGroups": ["name"],
  29.                         },
  30.                         "auth": authtoken,
  31.                         "id": 0
  32.                   }
  33.         )

  34.         info = requests.post(url,query,headers=header)
  35.         result = info.json()['result']

  36.         for host in result:
  37.                 hostname = host['host']
  38.                 group_names = [ g['name'].encode('utf8') for g in host['groups'] ]
  39.                 print hostname, ':', ', '.join(group_names)


  40. if __name__ == '__main__':
  41.         url = " />
  42.         header = {"Content-Type": "application/json"}
  43.         Query("cailu","xxoo")

                                                                                                                                                                    wepiao_Cail

阅读(2640) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~