opijoiu 发表于 2016-1-25 08:49:47

从zabbix数据库中获取ip列表

我把监控作为中心节点,所以所有IP地址都从zabbix中提取。

从zabbix数据库中提取IP,有两种方法:
(1)直接模糊查询hosts表:
比如查询运维部门的ip:select host from hosts where name like "op%" order by host;

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')

def get_ip():
    file = open('op_hosts', 'w')
    file.truncate()

    con = MySQLdb.connect(host='localhost',user='zabbix',passwd='zabbix',db='zabbix',charset='utf8')
    cur = con.cursor()

    cur.execute('select host from hosts where name like "op%" order by host;')
    file = open('op_hosts', 'a')
    for data in cur.fetchall():
      file.write(data + '\n')

if __name__=="__main__":
    get_ip()





(2)根据不同组进行查询:
先从groups表中获取groupid
再从hosts_groups表中获取属于该组的hostid
最后从hosts表中获取host和name

完整代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')

def get_ip():
    ipdir = '/root/ip'
    for i in os.listdir(ipdir):
      file = open(os.path.join(ipdir, i), 'w')
      file.truncate()

    con = MySQLdb.connect(host='localhost',user='zabbix',passwd='zabbix',db='zabbix',charset='utf8')
    cur = con.cursor()

    cur.execute('select host, name from hosts where hostid in (select hostid from hosts_groups where groupid in (select groupid from groups where groupid="8")) order by name;')
    file = open('/root/ip/linux', 'a')
    for data in cur.fetchall():
      file.write(data + ' ' + data + '\n')

if __name__=="__main__":
    get_ip()



页: [1]
查看完整版本: 从zabbix数据库中获取ip列表