从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()
完整代码如下:
#!/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()