zabbix自动发现的python方式数据生成

前言

zabbix里面有个功能是自动发现,比如文件系统和网卡的获取的时候,因为预先无法知道这个网卡的名称,所以就有了这个自动发现的功能,这里我是因为要用到存储池的自动发现,所以需要对数据进行生成

实现

我们看下原生的接口的数据类型:

1
2
[root@lab8106 ~]# zabbix_get -s 127.0.0.1 -k "net.if.discovery"
{"data":[{"{#IFNAME}":"enp3s0"},{"{#IFNAME}":"virbr0-nic"},{"{#IFNAME}":"docker0"},{"{#IFNAME}":"enp4s0"},{"{#IFNAME}":"enp2s0f0"},{"{#IFNAME}":"enp2s0f1"},{"{#IFNAME}":"virbr0"},{"{#IFNAME}":"lo"}]}

数据为格式化好了的json数据,这个地方弄了好半天,因为网上很多人是用字符串拼接的方式,实际这个是字典嵌套了列表,列表又嵌套了字典,就是后面的地方开始没弄懂怎么有大括号的

我们同样的来看看ceph原生的命令的json接口

1
2
3
4
[root@lab8106 ~]# ceph -s -f json

{"health":{"health":{"health_services":[{"mons":[{"name":"lab8106","kb_total":52403200,"kb_used":32905432,"kb_avail":19497768,"avail_percent":37,"last_updated":"2016-10-28 01:15:29.431854","store_stats"{"bytes_total":20206814,"bytes_sst":16929998,"bytes_log":3080192,"bytes_misc":196624,"last_updated":"0.000000"},"health":"HEALTH_OK"}]}]},"timechecks":{"epoch":4,"round":0,"round_status":"finished"},"summary":[],"overall_status":"HEALTH_OK","detail":[]},"fsid":"fae7a8db-c671-4b45-a784-ddb41e633905","election_epoch":4,"quorum":[0],"quorum_names":["lab8106"],"monmap":{"epoch":1,"fsid":"fae7a8db-c671-4b45-a784-ddb41e633905","modified":"2016-10-19 22:26:28.879232","created":"2016-10-19 22:26:28.879232","mons":[{"rank":0,"name":"lab8106","addr":"192.168.8.106:6789\/0"}]},"osdmap":{"osdmap":{"epoch":63,"num_osds":2,"num_up_osds":2,"num_in_osds":2,"full":false,"nearfull":false,"num_remapped_pgs":0}},"pgmap":{"pgs_by_state":[{"state_name":"active+clean","count":80}],"version":19174,"num_pgs":80,"data_bytes":45848191333,"bytes_used":45966077952,"bytes_avail":551592390656,"bytes_total":597558468608},"fsmap":{"epoch":5,"id":1,"up":1,"in":1,"max":1,"by_rank":[{"filesystem_id":1,"rank":0,"name":"lab8106","status":"up:active"}]}}

同样也是这个类型的数据,好了,这里直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def get_cluster_pools():
try:
pool_list=[]
data_dic = {}
cluster_pools = commands.getoutput('timeout 10 ceph osd pool ls -f json 2>/dev/null')
json_str = json.loads(cluster_pools)
for item in json_str:
pool_dic = {}
pool_dic['{#POOLNAME}'] = str(item)
pool_list.append(pool_dic)
data_dic['data'] = pool_list
return json.dumps(data_dic,separators=(',', ':'))
except:
return 0

输出如下

1
{"data":[{"{#POOLNAME}":"rbd"},{"{#POOLNAME}":"metedata"},{"{#POOLNAME}":"data"}]}

跟上面的格式一样了,关键在对字典进行赋值的处理,然后进行一个空格处理就完成了

总结

还是接触的太少,造成简单的处理都需要花费比较久的时间

变更记录

Why Who When
创建 武汉-运维-磨渣 2016-10-28