Projet

Général

Profil

Révision 7cf2dda9

ID7cf2dda94a06a2c27713b86ee3951bb1ee270158
Parent 8152186b
Enfant 51864405

Ajouté par Lars Kruse il y a environ 5 ans

Plugin snmp__juniper: migrate to Python3

Voir les différences:

plugins/router/snmp__juniper
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3

  
4
# Copyright (C) 2014 Johann Schmitz <johann@j-schmitz.net>
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU Library General Public License as published by
8
# the Free Software Foundation; version 2 only
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU Library General Public License for more details.
14
#
15
# You should have received a copy of the GNU Library General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18
#
19

  
1
#!/usr/bin/env python3
20 2
"""
21 3
=head1 NAME
22 4

  
......
27 9
Make sure your Juniper device is accessible via SNMP (e.g. via snmpwalk) and the munin-node
28 10
has been configured correctly.
29 11

  
30
=head1 MAGIC MARKERS
31

  
32
	#%# family=snmpauto
33
	#%# capabilities=snmpconf
34

  
35 12
=head1 VERSION
36 13

  
37 14
0.0.1
......
42 19

  
43 20
=head1 AUTHOR
44 21

  
45
Johann Schmitz <johann@j-schmitz.net>
22
Copyright (C) 2014 Johann Schmitz <johann@j-schmitz.net>
23

  
46 24

  
47 25
=head1 LICENSE
48 26

  
49
GPLv2
27
This program is free software; you can redistribute it and/or modify
28
it under the terms of the GNU Library General Public License as published by
29
the Free Software Foundation; version 2 only
30

  
31
This program is distributed in the hope that it will be useful,
32
but WITHOUT ANY WARRANTY; without even the implied warranty of
33
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34
GNU Library General Public License for more details.
35

  
36
You should have received a copy of the GNU Library General Public License
37
along with this program; if not, write to the Free Software
38
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39

  
40
SPDX-License-Identifier: GPL-2.0-only
41

  
42

  
43
=head1 MAGIC MARKERS
44

  
45
    #%# family=snmpauto
46
    #%# capabilities=snmpconf
50 47

  
51 48
=cut
52 49
"""
......
65 62
debug = bool(os.getenv('MUNIN_DEBUG', os.getenv('DEBUG', 0)))
66 63

  
67 64
if debug:
68
	logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-7s %(message)s')
65
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-7s %(message)s')
69 66

  
70 67
try:
71
	match = re.search("^(?:|.*\/)snmp_([^_]+)_juniper$", sys.argv[0])
72
	host = match.group(1)
73
	request = match.group(2)
74
	match = re.search("^([^:]+):(\d+)$", host)
75
	if match is not None:
76
		host = match.group(1)
77
		port = match.group(2)
78
except:
79
	pass
68
    match = re.search(r"^(?:|.*/)snmp_([^_]+)_juniper$", sys.argv[0])
69
    host = match.group(1)
70
    request = match.group(2)
71
    match = re.search(r"^([^:]+):(\d+)$", host)
72
    if match is not None:
73
        host = match.group(1)
74
        port = match.group(2)
75
except Exception:
76
    pass
80 77

  
81 78
jnxOperatingTable = '1.3.6.1.4.1.2636.3.1.13.1.5'
82 79

  
......
84 81
jnxOperatingCPU = '1.3.6.1.4.1.2636.3.1.13.1.8'
85 82
jnxOperatingBuffer = '1.3.6.1.4.1.2636.3.1.13.1.11'
86 83

  
84

  
87 85
class JunOSSnmpClient(object):
88
	def __init__(self, host, port, community):
89
		self.hostname = host
90
		self.transport = cmdgen.UdpTransportTarget((host, int(port)))
91
		self.auth = cmdgen.CommunityData('test-agent', community)
92
		self.gen = cmdgen.CommandGenerator()
93

  
94
	def get_devices(self):
95
		errorIndication, errorStatus, errorIndex, varBindTable = self.gen.bulkCmd(
96
			self.auth,
97
			self.transport,
98
			0, 20,
99
			jnxOperatingTable)
100
#			ignoreNonIncreasingOids=True) # only available with pysnmp >= 4.2.4 (?)
101

  
102
		if errorIndication:
103
			logging.error("SNMP bulkCmd for devices failed: %s, %s, %s" % (errorIndication, errorStatus, errorIndex))
104
			return {}
105

  
106
		devices = {}
107
		for row in varBindTable:
108
			for name, value in row:
109
				if not str(name).startswith(jnxOperatingTable):
110
					continue
111

  
112
				if 'Routing Engine' in str(value):
113
					devices[str(name)[len(jnxOperatingTable):]] = re.sub("[^\w]", '_', str(value).replace(' Routing Engine', ''))
114
		return devices
115

  
116
	def get_one(self, prefix_oid, suffix):
117
		oid = prefix_oid + suffix
118
		errorIndication, errorStatus, errorIndex, varBindTable = self.gen.getCmd(
119
			self.auth,
120
			self.transport,
121
			oid)
122

  
123
		if errorIndication:
124
			logging.error("SNMP getCmd for %s failed: %s, %s, %s" % (oid, errorIndication, errorStatus, errorIndex))
125
			return None
126

  
127
		return int(varBindTable[0][1])
128

  
129

  
130

  
131
	def get_data(self):
132
		devs = self.get_devices()
133

  
134
		return {
135
			'temp': dict([(name, self.get_one(jnxOperatingTemp, suffix)) for suffix, name in devs.iteritems()]),
136
			'cpu': dict([(name, self.get_one(jnxOperatingCPU, suffix)) for suffix, name in devs.iteritems()]),
137
			'buffer': dict([(name, self.get_one(jnxOperatingBuffer, suffix)) for suffix, name in devs.iteritems()]),
138
		}
139

  
140
	def print_config(self):
141
		devices = self.get_devices()
142

  
143
		data_def = [
144
			('temp', self.hostname, 'System temperature', '--base 1000', 'System temperature in C'),
145
			('cpu', self.hostname, 'CPU usage', '--base 1000 -l 0 --upper-limit 100', 'CPU usage in %'),
146
			('buffer', self.hostname, 'Buffer usage', '--base 1000 -l 0 --upper-limit 100', 'Buffer usage in %'),
147
		]
148

  
149
		for datarow, hostname, title, args, vlabel in data_def:
150
			print """multigraph juniper_{datarow}
86
    def __init__(self, host, port, community):
87
        self.hostname = host
88
        self.transport = cmdgen.UdpTransportTarget((host, int(port)))
89
        self.auth = cmdgen.CommunityData('test-agent', community)
90
        self.gen = cmdgen.CommandGenerator()
91

  
92
    def get_devices(self):
93
        errorIndication, errorStatus, errorIndex, varBindTable = self.gen.bulkCmd(
94
            self.auth,
95
            self.transport,
96
            0, 20,
97
            jnxOperatingTable)
98
        # the following line is only available with pysnmp >= 4.2.4 (?)
99
        # ignoreNonIncreasingOids=True)
100

  
101
        if errorIndication:
102
            logging.error("SNMP bulkCmd for devices failed: %s, %s, %s"
103
                          % (errorIndication, errorStatus, errorIndex))
104
            return {}
105

  
106
        devices = {}
107
        for row in varBindTable:
108
            for name, value in row:
109
                if not str(name).startswith(jnxOperatingTable):
110
                    continue
111

  
112
                if 'Routing Engine' in str(value):
113
                    devices[str(name)[len(jnxOperatingTable):]] = re.sub(
114
                        r"[^\w]", '_', str(value).replace(' Routing Engine', ''))
115
        return devices
116

  
117
    def get_one(self, prefix_oid, suffix):
118
        oid = prefix_oid + suffix
119
        errorIndication, errorStatus, errorIndex, varBindTable = self.gen.getCmd(
120
            self.auth,
121
            self.transport,
122
            oid)
123

  
124
        if errorIndication:
125
            logging.error("SNMP getCmd for %s failed: %s, %s, %s"
126
                          % (oid, errorIndication, errorStatus, errorIndex))
127
            return None
128

  
129
        return int(varBindTable[0][1])
130

  
131
    def get_data(self):
132
        devs = self.get_devices()
133

  
134
        return {
135
            'temp': dict([(name, self.get_one(jnxOperatingTemp, suffix))
136
                          for suffix, name in devs.items()]),
137
            'cpu': dict([(name, self.get_one(jnxOperatingCPU, suffix))
138
                         for suffix, name in devs.items()]),
139
            'buffer': dict([(name, self.get_one(jnxOperatingBuffer, suffix))
140
                            for suffix, name in devs.items()]),
141
        }
142

  
143
    def print_config(self):
144
        devices = self.get_devices()
145

  
146
        data_def = [
147
            ('temp', self.hostname, 'System temperature', '--base 1000',
148
             'System temperature in C'),
149
            ('cpu', self.hostname, 'CPU usage', '--base 1000 -l 0 --upper-limit 100',
150
             'CPU usage in %'),
151
            ('buffer', self.hostname, 'Buffer usage', '--base 1000 -l 0 --upper-limit 100',
152
             'Buffer usage in %'),
153
        ]
154

  
155
        for datarow, hostname, title, args, vlabel in data_def:
156
            print("""multigraph juniper_{datarow}
151 157
host_name {hostname}
152 158
graph_title {title}
153 159
graph_vlabel {vlabel}
154 160
graph_args {args}
155 161
graph_category fw
156
graph_info {title}""".format(datarow=datarow, hostname=hostname, title=title, args=args, vlabel=vlabel)
162
graph_info {title}""".format(datarow=datarow, hostname=hostname, title=title, args=args,
163
                             vlabel=vlabel))
157 164

  
158
			for suffix, node in devices.iteritems():
159
				ident = "%s_%s" % (datarow, node)
160
				print """{label}.info {title} on {node}
165
            for suffix, node in devices.items():
166
                ident = "%s_%s" % (datarow, node)
167
                print("""{label}.info {title} on {node}
161 168
{label}.label {node}
162 169
{label}.type GAUGE
163
{label}.min 0""".format(title=title, label=ident, node=node)
170
{label}.min 0""".format(title=title, label=ident, node=node))
171

  
172
    def execute(self):
173
        data = self.get_data()
164 174

  
165
	def execute(self):
166
		data = self.get_data()
175
        for pre, values in data.items():
176
            print("multigraph juniper_%s" % pre)
177
            for node, value in values.items():
178
                print("%s_%s.value %s" % (pre, node, value))
167 179

  
168
		for pre, values in data.iteritems():
169
			print "multigraph juniper_%s" % pre
170
			for node, value in values.iteritems():
171
				print "%s_%s.value %s" % (pre, node, value)
172 180

  
173 181
c = JunOSSnmpClient(host, port, community)
174 182

  
183

  
175 184
if "snmpconf" in sys.argv[1:]:
176
	print "require 1.3.6.1.4.1.2636.3.1.13.1.5"
177
	sys.exit(0)
185
    print("require 1.3.6.1.4.1.2636.3.1.13.1.5")
186
    sys.exit(0)
178 187
else:
179
	if not (host and port and community):
180
		print "# Bad configuration. Cannot run with Host=%s, port=%s and community=%s" % (host, port, community)
181
		sys.exit(1)
182

  
183
	if "config" in sys.argv[1:]:
184
		c.print_config()
185
	else:
186
		c.execute()
188
    if not (host and port and community):
189
        print("# Bad configuration. Cannot run with Host=%s, port=%s and community=%s"
190
              % (host, port, community), file=sys.stderr)
191
        sys.exit(1)
192

  
193
    if "config" in sys.argv[1:]:
194
        c.print_config()
195
    else:
196
        c.execute()
t/test-exception-wrapper.expected-failures
400 400
plugins/router/dsl-stats
401 401
plugins/router/freeboxuptime
402 402
plugins/router/motorola_sb6141
403
plugins/router/snmp__juniper
404 403
plugins/router/snmp__linksys_poe
405 404
plugins/router/speedport_300
406 405
plugins/rsync/rsyncd_bytes

Formats disponibles : Unified diff