python-Django监控系统二次开发Nagios

时间:2022-11-30 16:22:02

1、Nagios安装

yum install -y nagios.i686

yum install -y nagios-plugins-all.i686

安装完后会在apache的配置文件目录下/etc/httpd/conf.d/产生一个外部的配置文件nagios.conf

service httpd start

service nagios start

default user nagiosadmin password nagiosadmin

2.配置文件生成器

Django前期的收集主机信息代码

优化后:

 #!/usr/bin/env python

 import urllib,urllib2
from subprocess import Popen,PIPE
import pickle
import json def getIfconfig():
p = Popen(['ifconfig'],stdout=PIPE)
data = p.stdout.read()
return data def getDmi():
p = Popen(['dmidecode'],stdout=PIPE,stderr=PIPE)
data_out = p.stdout.read()
data_err = p.stderr.read()
if data_err:
return {'vendor':'container','product':'container','sn':'XXX'}
return data_out def parseData(data):
if isinstance(data,dict):
return data
parsed_data = []
new_line = ''
data = [i for i in data.split('\n') if i]
for line in data:
if line[0].strip():
parsed_data.append(new_line)
new_line = line +'\n'
else:
new_line += line+'\n'
parsed_data.append(new_line)
return [i for i in parsed_data if i] def parseIfconfig(parsed_data):
parsed_data = [i for i in parsed_data if not i.startswith('lo')]
for lines in parsed_data:
line_list = lines.split('\n')
devname = line_list[0].split()[0]
macaddr = line_list[0].split()[-1]
ipaddr = line_list[1].split()[1].split(':')[1]
break
dic['ip'] =ipaddr
return dic def parseDmi(parsed_data):
if isinstance(parsed_data,dict):
return parsed_data
dic = {}
parsed_data = [i for i in parsed_data if i.startswith('System Information')]
parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
dmi_dic = dict([i.strip().split(':') for i in parsed_data])
dic['vendor'] = dmi_dic['Manufacturer'].strip()
dic['product'] = dmi_dic['Product Name'].strip()
dic['sn'] = dmi_dic['Serial Number'].strip()[:15]
return dic def getHostname(f):
with open(f) as fd:
for line in fd:
if line.startswith('HOSTNAME'):
hostname = line.split('=')[1].strip()
break
return {'hostname':hostname} def getOsver(f):
with open(f) as fd:
for line in fd:
osver = line.strip()
break
return {'osver':osver} def getCpu(f):
num = 0
with open(f) as fd:
for line in fd:
if line.startswith('processor'):
num +=1
if line.startswith('model name'):
cpu_model = line.split(':')[1].split()
cpu_model = cpu_model[0]+' '+cpu_model[-1]
return {'cpu_num':num,'cpu_model':cpu_model} def getMemory(f):
with open(f) as fd:
for line in fd:
if line.startswith('MemTotal'):
mem = int(line.split()[1].strip())
break
mem = "%d" % int(mem/1024.0)+'M'
return {'memory':mem} if __name__ == '__main__':
dic = {}
data_ip = getIfconfig()
parsed_data_ip = parseData(data_ip)
ip = parseIfconfig(parsed_data_ip)
data_dmi = getDmi()
parsed_data_dmi = parseData(data_dmi)
dmi = parseDmi(parsed_data_dmi)
hostname = getHostname('/etc/sysconfig/network')
osver = getOsver('/etc/issue')
cpu = getCpu('/proc/cpuinfo')
mem = getMemory('/proc/meminfo')
dic.update(ip)
dic.update(dmi)
dic.update(hostname)
dic.update(osver)
dic.update(cpu)
dic.update(mem)
#data = urllib.urlencode(dic)
#data = pickle.dumps(dic)
data = json.dumps(dic)
req = urllib2.urlopen('http://192.168.1.120:8000/hostinfo/collect/',data)
print req.read()

在nagios上分组

vim gen.py

 #!/usr/bin/env python

 import os
import urllib,urllib2
import json CUR_DIR = os.path.dirname(__file__)
CONF_DIR = os.path.join(os.path.abspath(CUR_DIR),'hosts') HOST_TEMP="""define host{
use linux-server
host_name %(hostname)s
alias %(hostname)s
address %(ip)s
}
"""
HOSTGROUP_TEMP="""define hostgroup{
hostgroup_name %(groupname)s
alias %(groupname)s
members %(members)s
}
"""
def initDir():
if not os.path.exists(CONF_DIR):
os.mkdir(CONF_DIR) def getData():
url = 'http://192.168.1.120:8000/hostinfo/getjson/'
req = urllib2.urlopen(url)
data = json.loads(req.read())
return data def writeConf(f,data):
with open(f,'w') as fd:
fd.write(data) def parseData(data):
host_conf = ''
hostgroup_conf = ''
for hg in data:
groupname = hg['groupname']
members = []
for h in hg['members']:
hostname = h['hostname']
members.append(hostname)
host_conf += HOST_TEMP % h
hostgroup_conf += HOSTGROUP_TEMP % {'groupname':groupname, 'members':','.join(members)}
fp_hostconf = os.path.join(CONF_DIR,'hosts.cfg')
fp_hostgroupconf = os.path.join(CONF_DIR,'hostgroup.cfg')
writeConf(fp_hostconf,host_conf)
writeConf(fp_hostgroupconf,hostgroup_conf) if __name__ == '__main__':
initDir()
data = getData()
parseData(data)

gen.py

同步配置文件sync_gen.sh

 #!/bin/bash

 cur=`dirname $0`
cd $cur
python gen.py
md5=`find hosts/ -type f -exec md5sum {} \;|md5sum`
cd /etc/nagios/conf.d
conf_md5=`find hosts/ -type f -exec md5sum {} \;|md5sum`
if [ "$md5" != "$conf_md5" ];then
cd -
cp -rp hosts/ /etc/nagios/conf.d
/etc/init.d/nagios restart
fi

如果两个分组都有一样的信息,即一样的主机名,则需加判断条件:

 #!/usr/bin/env python

 import os
import urllib,urllib2
import json CUR_DIR = os.path.dirname(__file__)
CONF_DIR = os.path.join(os.path.abspath(CUR_DIR),'hosts') HOST_TEMP="""define host{
use linux-server
host_name %(hostname)s
alias %(hostname)s
address %(ip)s
}
"""
HOSTGROUP_TEMP="""define hostgroup{
hostgroup_name %(groupname)s
alias %(groupname)s
members %(members)s
}
"""
def initDir():
if not os.path.exists(CONF_DIR):
os.mkdir(CONF_DIR) def getData():
url = 'http://192.168.1.120:8000/hostinfo/getjson/'
req = urllib2.urlopen(url)
data = json.loads(req.read())
return data def writeConf(f,data):
with open(f,'w') as fd:
fd.write(data) def countDict(k,d):
if k in d:
d[k] += 1
else:
d[k] = 1 def parseData(data):
dic = {}
host_conf = ''
hostgroup_conf = ''
for hg in data:
groupname = hg['groupname']
members = []
for h in hg['members']:
hostname = h['hostname']
members.append(hostname)
countDict(hostname,dic)
if dic(hostname) < 2:
host_conf += HOST_TEMP % h
hostgroup_conf += HOSTGROUP_TEMP % {'groupname':groupname, 'members':','.join(members)}
fp_hostconf = os.path.join(CONF_DIR,'hosts.cfg')
fp_hostgroupconf = os.path.join(CONF_DIR,'hostgroup.cfg')
writeConf(fp_hostconf,host_conf)
writeConf(fp_hostgroupconf,hostgroup_conf) if __name__ == '__main__':
initDir()
data = getData()
parseData(data)