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

时间:2021-11-08 05:38:49

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前期的收集主机信息代码

优化后:

  1 #!/usr/bin/env python
  2 
  3 import urllib,urllib2
  4 from subprocess import Popen,PIPE
  5 import pickle
  6 import json
  7 
  8 def getIfconfig():
  9     p = Popen(['ifconfig'],stdout=PIPE)
 10     data = p.stdout.read()
 11     return data
 12 
 13 def getDmi():
 14     p = Popen(['dmidecode'],stdout=PIPE,stderr=PIPE)
 15     data_out = p.stdout.read()
 16     data_err = p.stderr.read()
 17     if data_err:
 18         return {'vendor':'container','product':'container','sn':'XXX'}
 19     return data_out
 20 
 21 def parseData(data):
 22     if isinstance(data,dict):
 23         return data
 24     parsed_data = []
 25     new_line = ''
 26     data = [i for i in data.split('\n') if i]
 27     for line in data:
 28         if line[0].strip():
 29              parsed_data.append(new_line)
 30             new_line = line +'\n'
 31         else:        
 32             new_line += line+'\n'
 33     parsed_data.append(new_line)
 34     return [i for i in parsed_data if i]
 35 
 36 def parseIfconfig(parsed_data):
 37     parsed_data = [i for i in parsed_data if not i.startswith('lo')]
 38     for lines in parsed_data:
 39         line_list = lines.split('\n')
 40         devname = line_list[0].split()[0]
 41         macaddr = line_list[0].split()[-1]
 42         ipaddr = line_list[1].split()[1].split(':')[1]
 43         break
 44     dic['ip'] =ipaddr
 45     return dic
 46 
 47 def parseDmi(parsed_data):
 48     if isinstance(parsed_data,dict):
 49         return parsed_data
 50     dic = {}
 51     parsed_data = [i for i in parsed_data if i.startswith('System Information')]
 52     parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i]
 53     dmi_dic =  dict([i.strip().split(':') for i in parsed_data])
 54     dic['vendor'] = dmi_dic['Manufacturer'].strip()
 55     dic['product'] = dmi_dic['Product Name'].strip()
 56     dic['sn'] = dmi_dic['Serial Number'].strip()[:15]
 57     return dic
 58 
 59 def getHostname(f):
 60     with open(f) as fd:
 61         for line in fd:
 62             if line.startswith('HOSTNAME'):
 63                 hostname = line.split('=')[1].strip()
 64                 break
 65     return {'hostname':hostname}
 66 
 67 def getOsver(f):
 68     with open(f) as fd:
 69         for line in fd:
 70             osver = line.strip()
 71             break
 72     return {'osver':osver}
 73 
 74 def getCpu(f):
 75     num = 0
 76     with open(f) as fd:
 77         for line in fd:
 78             if line.startswith('processor'):
 79                 num +=1
 80             if line.startswith('model name'):
 81                 cpu_model = line.split(':')[1].split()
 82                 cpu_model = cpu_model[0]+' '+cpu_model[-1]
 83     return {'cpu_num':num,'cpu_model':cpu_model}
 84 
 85 def getMemory(f):
 86     with open(f) as fd:
 87         for line in fd:
 88             if line.startswith('MemTotal'):
 89                 mem = int(line.split()[1].strip())
 90                 break
 91     mem = "%d" % int(mem/1024.0)+'M'
 92     return {'memory':mem}
 93                 
 94 
 95 if __name__ == '__main__':
 96     dic = {}
 97     data_ip = getIfconfig()
 98     parsed_data_ip = parseData(data_ip)
 99     ip = parseIfconfig(parsed_data_ip)
100     data_dmi = getDmi()
101     parsed_data_dmi = parseData(data_dmi)
102     dmi = parseDmi(parsed_data_dmi)
103     hostname = getHostname('/etc/sysconfig/network')
104     osver = getOsver('/etc/issue')
105     cpu = getCpu('/proc/cpuinfo')
106     mem = getMemory('/proc/meminfo')
107     dic.update(ip)
108     dic.update(dmi)
109     dic.update(hostname)
110     dic.update(osver)
111     dic.update(cpu)
112     dic.update(mem)
113     #data = urllib.urlencode(dic)
114     #data = pickle.dumps(dic)
115     data = json.dumps(dic)
116     req = urllib2.urlopen('http://192.168.1.120:8000/hostinfo/collect/',data)
117     print req.read()

 

在nagios上分组

vim gen.py

python-Django监控系统二次开发Nagiospython-Django监控系统二次开发Nagios
 1 #!/usr/bin/env python
 2 
 3 import os
 4 import urllib,urllib2
 5 import json
 6 
 7 CUR_DIR = os.path.dirname(__file__)
 8 CONF_DIR = os.path.join(os.path.abspath(CUR_DIR),'hosts')
 9 
10 HOST_TEMP="""define host{
11                 use             linux-server
12                 host_name       %(hostname)s
13                 alias           %(hostname)s
14                 address         %(ip)s
15                 }
16         """
17 HOSTGROUP_TEMP="""define hostgroup{
18         hostgroup_name  %(groupname)s
19         alias           %(groupname)s
20         members         %(members)s
21         }
22     """
23 def initDir():
24     if not os.path.exists(CONF_DIR):
25         os.mkdir(CONF_DIR)
26 
27 def getData():
28     url = 'http://192.168.1.120:8000/hostinfo/getjson/'
29         req = urllib2.urlopen(url)
30         data = json.loads(req.read())
31     return data
32 
33 def writeConf(f,data):
34         with open(f,'w') as fd:
35                 fd.write(data)
36 
37 def parseData(data):
38     host_conf = ''
39     hostgroup_conf = ''
40     for hg in data:
41         groupname = hg['groupname']
42         members = []
43         for h in hg['members']:
44             hostname = h['hostname']
45             members.append(hostname)
46             host_conf += HOST_TEMP % h
47         hostgroup_conf += HOSTGROUP_TEMP % {'groupname':groupname, 'members':','.join(members)}
48     fp_hostconf = os.path.join(CONF_DIR,'hosts.cfg')
49     fp_hostgroupconf = os.path.join(CONF_DIR,'hostgroup.cfg')
50     writeConf(fp_hostconf,host_conf)
51     writeConf(fp_hostgroupconf,hostgroup_conf)
52 
53 
54 if __name__ == '__main__':
55     initDir()
56     data = getData()
57     parseData(data)
gen.py

 同步配置文件sync_gen.sh

 1 #!/bin/bash
 2 
 3 cur=`dirname $0`
 4 cd $cur
 5 python gen.py
 6 md5=`find hosts/ -type f -exec md5sum {} \;|md5sum`
 7 cd /etc/nagios/conf.d
 8 conf_md5=`find hosts/ -type f -exec md5sum {} \;|md5sum`
 9 if [ "$md5" != "$conf_md5" ];then
10     cd -
11     cp -rp hosts/ /etc/nagios/conf.d
12     /etc/init.d/nagios restart
13 fi

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

 1 #!/usr/bin/env python
 2 
 3 import os
 4 import urllib,urllib2
 5 import json
 6 
 7 CUR_DIR = os.path.dirname(__file__)
 8 CONF_DIR = os.path.join(os.path.abspath(CUR_DIR),'hosts')
 9 
10 HOST_TEMP="""define host{
11                 use             linux-server
12                 host_name       %(hostname)s
13                 alias           %(hostname)s
14                 address         %(ip)s
15                 }
16         """
17 HOSTGROUP_TEMP="""define hostgroup{
18         hostgroup_name  %(groupname)s
19         alias           %(groupname)s
20         members         %(members)s
21         }
22     """
23 def initDir():
24     if not os.path.exists(CONF_DIR):
25         os.mkdir(CONF_DIR)
26 
27 def getData():
28     url = 'http://192.168.1.120:8000/hostinfo/getjson/'
29         req = urllib2.urlopen(url)
30         data = json.loads(req.read())
31     return data
32 
33 def writeConf(f,data):
34         with open(f,'w') as fd:
35                 fd.write(data)
36 
37 def countDict(k,d):
38     if k in d:
39         d[k] += 1
40     else:
41          d[k] = 1
42 
43 def parseData(data):
44     dic = {}
45     host_conf = ''
46     hostgroup_conf = ''
47     for hg in data:
48         groupname = hg['groupname']
49         members = []
50         for h in hg['members']:
51             hostname = h['hostname']
52             members.append(hostname)
53             countDict(hostname,dic)
54             if dic(hostname) < 2:
55                 host_conf += HOST_TEMP % h
56         hostgroup_conf += HOSTGROUP_TEMP % {'groupname':groupname, 'members':','.join(members)}
57     fp_hostconf = os.path.join(CONF_DIR,'hosts.cfg')
58     fp_hostgroupconf = os.path.join(CONF_DIR,'hostgroup.cfg')
59     writeConf(fp_hostconf,host_conf)
60     writeConf(fp_hostgroupconf,hostgroup_conf)
61 
62 
63 if __name__ == '__main__':
64     initDir()
65     data = getData()
66     parseData(data)