我把监控作为中心节点,所以所有IP地址都从zabbix中提取。
从zabbix数据库中提取IP,有两种方法:
(1)直接模糊查询hosts表:
比如查询运维部门的ip:select host from hosts where name like "op%" order by host;
完整代码如下:
#!/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[0] + ‘\n‘) if __name__=="__main__": get_ip()
(2)根据不同组进行查询:
先从groups表中获取groupid
在从hosts_groups表中获取属于该组的hostid
最后从hosts表中获取host和name
完整代码如下:
#!/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[0] + ‘ ‘ + data[1] + ‘\n‘) if __name__=="__main__": get_ip()
时间: 2024-10-14 19:43:53