├── .gitignore
├── LICENSE
├── README.md
├── cacti
├── flexlmMonitor
│ ├── flexlm-feature-monitor.py
│ └── lmutil
├── oge-jobs.py
└── oge-queue.py
├── nagios
├── check-cisco-po.pl
├── check-cisco.example
├── check-cisco.pl
├── check-file-exists.pl
├── check-juniper-vpn.pl
├── check-netapp-ng.pl
├── check-paloalto-A500.pl
├── check-pineapp.pl
├── check-roomalert.pl
├── check_activemq.py
├── check_deep_fs.py
├── check_flexlm.pl
├── check_flexlm_up.sh
├── check_internet.sh
├── check_modjk.py
├── check_sgeexec.pl
├── check_solr.py
├── check_svn.sh
├── check_w32_mem.pl
├── perf-linux-cpu.pl
├── perf-sge.pl
├── perf_ghs-float.sh
└── pnp
│ ├── check-cisco-cpu.php
│ ├── check-cisco-fan.php
│ ├── check-cisco-freeint.php
│ ├── check-cisco-mem.php
│ ├── check-cisco-module.php
│ ├── check-cisco-ps.php
│ ├── check-cisco-totalbw.php
│ ├── check-juniper-vpn-load.php
│ ├── check-juniper-vpn-mem.php
│ ├── check-juniper-vpn-swap.php
│ ├── check-pineapp-inout.php
│ ├── check-pineapp-load.php
│ ├── check-pineapp-queue.php
│ ├── check_cpus_linux.php
│ ├── check_flexlm_new.php
│ ├── check_load_srv.php
│ ├── perf-ghs-float.php
│ ├── perf-sge-cjs.php
│ └── perf-sge-qjs.php
└── zabbix
├── scripts
├── activemq-monitor.py
├── list_ips.py
├── rss.py
├── smx-bundle.py
└── solr.py
└── user_param
├── apache.conf
├── fs_discovery.conf
├── mysql.conf
└── solr.conf
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea/
2 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | monitor-utils
2 | =============
3 |
4 | Monitoring script for Zabbix / Nagios
5 |
--------------------------------------------------------------------------------
/cacti/flexlmMonitor/flexlm-feature-monitor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # Info
4 | # parses lmstat utility to get license usage of a specific feature
5 |
6 | # Modules
7 | import subprocess
8 | import re
9 | import sys
10 | import os.path
11 |
12 | # Settings
13 | lmutil = os.path.dirname(sys.argv[0])
14 |
15 | # Validate settings
16 | if len(sys.argv) != 4 :
17 | print "Syntax error"
18 | print sys.argv[0] + ' [port] [server name] [feature]'
19 | quit(3)
20 | if os.path.isfile(lmutil) == False :
21 | print 'The lmutil binary ' + lmutil + ' does not exists'
22 | quit(3)
23 |
24 | # Vars
25 | port = sys.argv[1]
26 | server = sys.argv[2]
27 | feature = sys.argv[3]
28 | errorString = re.escape('Users of ' + feature + ': (Error:')
29 |
30 | # Initiate lmstat
31 | lmstat = subprocess.Popen([lmutil, 'lmstat' , '-c', port+'@'+server, '-f', feature], shell=False, stdout=subprocess.PIPE, stderr=None, stdin=None)
32 | out = lmstat.communicate()[0].splitlines( )
33 | exitCode = lmstat.returncode
34 | line2Parse = None
35 |
36 | # If an erroe occured -> out
37 | if exitCode != 0 :
38 | for line in out : print line
39 | quit(1)
40 |
41 | # search for the data in stdout
42 | for i in range(len(out)):
43 | if re.search(re.escape(feature), out[i]) :
44 | line2Parse = out[i]
45 | break
46 |
47 | # Make sure stdout is valid
48 | if line2Parse == None :
49 | print 'Can not find feature \"' + feature + '\" in host ' + port+'@'+server
50 | quit(1)
51 | elif re.search(errorString, line2Parse) :
52 | print 'Error in license server:'
53 | print line2Parse
54 | quit(1)
55 |
56 | # Host is up & Data is valid
57 | # parse usage
58 | usage = re.findall(r' \d\d* ', line2Parse)
59 | total = usage[len(usage)-2].strip()
60 | used = usage[len(usage)-1].strip()
61 |
62 | # Output usage
63 | sys.stdout.write('total:'+total + ' ' + 'used:' + used)
64 | quit(0);
65 |
--------------------------------------------------------------------------------
/cacti/flexlmMonitor/lmutil:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ranl/monitor-utils/fc9c1902abf740d36d857e3a879573a4ed1e0301/cacti/flexlmMonitor/lmutil
--------------------------------------------------------------------------------
/cacti/oge-jobs.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 |
3 | # Info
4 | # Check via the qhost command the number a running jobs on a specific execution host
5 | #
6 | # Settings
7 | # 1. set the gridSettings variable
8 | # 2. queues can be excluded by settings the excludeQueues list
9 | # 3. the cacti server needs to be configured as the submit host (qconf -as CACTISERVER)
10 |
11 | # Modules
12 | import subprocess
13 | import re
14 | import string
15 | import sys
16 |
17 | # Exclude function
18 | def isInList(string, dst) :
19 | res = False
20 | for i in range(len(dst)):
21 | if string == dst[i]:
22 | res = True
23 | break
24 | return res
25 |
26 |
27 | # Settings
28 | gridSettings = '/path/to/common/settings.sh'
29 | excludeQueues = []
30 |
31 | # Validate command arguments
32 | if len(sys.argv) != 2:
33 | print "Syntax error"
34 | print sys.argv[0] + ' [execHost]'
35 | quit(1)
36 |
37 | # Vars
38 | execHost = sys.argv[1]
39 | execHostEscaped = ''
40 | foundExecHost = False
41 | jobsCounter = 0
42 |
43 | # Initiate qhost -q
44 | qhost = subprocess.Popen('source ' + gridSettings + '; ' + 'qhost -q', shell=True, stdout=subprocess.PIPE, stderr=None, stdin=None)
45 | out = qhost.communicate()[0].splitlines( )
46 | exitCode = qhost.returncode
47 |
48 | # If an error occured -> quit
49 | if exitCode != 0 :
50 | for line in out : print line
51 | quit(1)
52 |
53 | # Parse out
54 | execHostEscaped = re.escape(execHost) + ' '
55 | for i in range(len(out)):
56 | if foundExecHost and re.search('^ ' ,out[i]) :
57 | if not isInList(out[i].split()[0], excludeQueues):
58 | jobsCounter += int(string.split(out[i].split()[2],'/')[0])
59 | elif foundExecHost and re.search('^\w' ,out[i]) :
60 | break
61 | else :
62 | if re.search(execHostEscaped, out[i]) :
63 | foundExecHost = True
64 |
65 | # Print Result
66 | if foundExecHost :
67 | sys.stdout.write('jobs:'+str(jobsCounter))
68 | else :
69 | sys.stdout.write('-1')
70 | quit(1)
71 |
--------------------------------------------------------------------------------
/cacti/oge-queue.py:
--------------------------------------------------------------------------------
1 | #!/bin/env python
2 |
3 | # Info:
4 | # Get queue usage via qstat -g c command
5 | # Note: it will exclude host in error/disable hosts
6 | #
7 | # Settings:
8 | # add the cacti server as submit host
9 | # set the gridSettings variable
10 |
11 | # Modules
12 | import subprocess
13 | import sys
14 |
15 | # Settings
16 | gridSettings = '/path/to/common/settings.sh'
17 |
18 | if len(sys.argv) != 2:
19 | print "Syntax error"
20 | print sys.argv[0] + ' [full queue name]'
21 | quit(1)
22 |
23 | # Vars
24 | queue = sys.argv[1]
25 | jobsCounter = 0
26 | foundQueue = False
27 | running = 0
28 | total = 0
29 |
30 | # Initiate qstat -g c
31 | qstat = subprocess.Popen('source ' + gridSettings + '; ' + 'qstat -g c', shell=True, stdout=subprocess.PIPE, stderr=None, stdin=None)
32 | out = qstat.communicate()[0].splitlines( )
33 | exitCode = qstat.returncode
34 |
35 | # If an error occured -> out
36 | if exitCode != 0 :
37 | for line in out : print line
38 | quit(1)
39 |
40 | # Parse out
41 | for i in range(len(out)):
42 | queueInfo = out[i].split()
43 | if queueInfo[0] == queue:
44 | foundQueue = True
45 | total = int(queueInfo[2]) + int(queueInfo[4])
46 | running = int(queueInfo[2])
47 |
48 | # Print Result
49 | if foundQueue :
50 | sys.stdout.write('total:'+str(total) + ' ' + 'running:'+str(running))
51 | else :
52 | sys.stdout.write('-1')
53 | quit(1)
54 |
--------------------------------------------------------------------------------
/nagios/check-cisco-po.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | # Modules
4 | use strict;
5 | use Net::SNMP;
6 | use Getopt::Long;
7 | Getopt::Long::Configure('bundling');
8 |
9 | # Interfaces
10 | my $S_int_entry = ".1.3.6.1.2.1.2.2.1";
11 | my $S_int_desc = "$S_int_entry.2";
12 | my $S_int_operstatus = "$S_int_entry.8";
13 | my $S_int_speed = '.1.3.6.1.2.1.31.1.1.1.15';
14 |
15 | # Status of operstatus
16 | my %int_status_index = (
17 | 1 => 'up',
18 | 2 => 'down',
19 | 3 => 'testing',
20 | 4 => 'unknown',
21 | 5 => 'notPresent',
22 | 6 => 'lowerLayerDown',
23 | );
24 |
25 | # Nagios Exit codes
26 | my $OK = 0;
27 | my $WARNING = 1;
28 | my $CRITICAL = 2;
29 | my $UNKNOWN = 3;
30 |
31 | # Output & exit code
32 | my $stat = $OK;
33 | my $msg;
34 | my $perf;
35 |
36 | ### Functions
37 | ###############
38 | sub _create_session
39 | {
40 | my ($server, $comm) = @_;
41 | my $version = 1;
42 | my ($sess, $err) = Net::SNMP->session( -hostname => $server, -version => $version, -community => $comm);
43 | if (!defined($sess)) {
44 | print "Can't create SNMP session to $server\n";
45 | exit(1);
46 | }
47 | return $sess;
48 | }
49 |
50 | sub _get_oid_value(@)
51 | {
52 | my $sess = shift;
53 | my $local_oid = shift;
54 | my $r_return = $sess->get_request(-varbindlist => [$local_oid]);
55 | return($r_return->{$local_oid});
56 | }
57 |
58 | sub _syntax_err(@)
59 | {
60 | my $msg = shift;
61 | print <get_table($S_int_desc);
95 | my $is_int_exists = 0;
96 | foreach my $oid ( keys %$R_tbl) {
97 | if($$R_tbl{$oid} =~ "[Pp]ort-channel$opt{'interface'}\$")
98 | {
99 | $snmpId = "$oid";
100 | $snmpId =~ s/$S_int_desc\.//;
101 | }
102 | }
103 |
104 | # Exit if non-were found
105 | _syntax_err("Can't find Port-channel$opt{'interface'}") if($snmpId eq "");
106 |
107 | # Check operstatus
108 | my $operationStatus = _get_oid_value($snmp_session,"$S_int_operstatus.$snmpId");
109 |
110 | # Quit if po is down totally
111 | if($operationStatus ne 1)
112 | {
113 | $stat = $CRITICAL;
114 | $msg = "CRIT: Port-channel$opt{'interface'} is $int_status_index{$operationStatus}";
115 | $perf = "upInts=0";
116 | }
117 |
118 | # Check speed of the po and cross reference with $opt{'numIfInts'}*$opt{'speed'};
119 | if($stat == $OK)
120 | {
121 | my $speed = _get_oid_value($snmp_session,"$S_int_speed.$snmpId");
122 | my $expectedSpeed = $opt{'numIfInts'} * $opt{'speed'};
123 | if($speed == $expectedSpeed) # Everthing is ok
124 | {
125 | $stat = $OK;
126 | $msg = "OK: Port-channel$opt{'interface'} is $int_status_index{$operationStatus}";
127 | $perf = "upInts=$opt{'numIfInts'}";
128 | }
129 | else # at least one or more interfaces are down, calculate how many
130 | {
131 | my $upInts = $opt{'numIfInts'} - int($speed / $opt{'speed'});
132 | $stat = $WARNING;
133 | $msg = "WARNING: $upInts/$opt{'numIfInts'} in Port-channel$opt{'interface'} are down";
134 | $perf = "upInts=$upInts";
135 | }
136 | }
137 |
138 | # Exit
139 | print "$msg | $perf\n";
140 | exit($stat);
141 |
142 |
--------------------------------------------------------------------------------
/nagios/check-cisco.example:
--------------------------------------------------------------------------------
1 | Commands.cfg
2 | -----------------
3 | define command {
4 | command_name cisco-module
5 | command_line $USER1$/check-cisco.pl -H $HOSTADDRESS$ -C $ARG1$ -t module -w $ARG2$ -c $ARG3$
6 | }
7 | define command {
8 | command_name cisco-temp
9 | command_line $USER1$/check-cisco.pl -H $HOSTADDRESS$ -C $ARG1$ -t temp -w $ARG2$ -c $ARG3$
10 | }
11 | define command {
12 | command_name cisco-fan
13 | command_line $USER1$/check-cisco.pl -H $HOSTADDRESS$ -C $ARG1$ -t fan
14 | }
15 | define command {
16 | command_name cisco-ps
17 | command_line $USER1$/check-cisco.pl -H $HOSTADDRESS$ -C $ARG1$ -t ps
18 | }
19 |
20 | define command {
21 | command_name cisco-int
22 | command_line $USER1$/check-cisco.pl -H $HOSTADDRESS$ -C $ARG1$ -t int -w $ARG2$ -c $ARG3$ -o $ARG4$
23 | }
24 | define command {
25 | command_name cisco-cpu
26 | command_line $USER1$/check-cisco.pl -H $HOSTADDRESS$ -C $ARG1$ -t cpu -w $ARG2$ -c $ARG3$
27 | }
28 | define command {
29 | command_name cisco-mem
30 | command_line $USER1$/check-cisco.pl -H $HOSTADDRESS$ -C $ARG1$ -t mem -w $ARG2$ -c $ARG3$
31 | }
32 |
--------------------------------------------------------------------------------
/nagios/check-cisco.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | use strict;
15 | use Net::SNMP;
16 | my $stat;
17 | my $msg;
18 | my $perf;
19 | my $days = 14;
20 | my $script_name = "check-cisco.pl";
21 |
22 | ### SNMP OIDs
23 | ###############
24 | # Temperature
25 | my $S_temp = ".1.3.6.1.4.1.9.9.13.1.3.1.3";
26 | # Memory
27 | my $S_mem_used = ".1.3.6.1.4.1.9.9.48.1.1.1.5.1"; # Byte
28 | my $S_mem_free = ".1.3.6.1.4.1.9.9.48.1.1.1.6.1"; # Byte
29 | # CPU Load
30 | my $S_load_5s = ".1.3.6.1.4.1.9.2.1.56.0";
31 | my $S_load_1m = ".1.3.6.1.4.1.9.2.1.57.0";
32 | my $S_load_5m = ".1.3.6.1.4.1.9.2.1.58.0";
33 | # Power Supply
34 | my $S_ps = ".1.3.6.1.4.1.9.9.13.1.5.1";
35 | my $S_ps_name = "$S_ps.2";
36 | my $S_ps_stat = "$S_ps.3";
37 | # Fan
38 | my $S_fan = ".1.3.6.1.4.1.9.9.13.1.4.1";
39 | my $S_fan_name = "$S_fan.2";
40 | my $S_fan_stat = "$S_fan.3";
41 | # Module
42 | my $S_module_status = ".1.3.6.1.4.1.9.9.117.1.2.1.1.2";
43 | # Interfaces
44 | my $S_int_entry = ".1.3.6.1.2.1.2.2.1";
45 | my $S_int_desc = "$S_int_entry.2";
46 | my $S_int_adminstatus = "$S_int_entry.7";
47 | my $S_int_operstatus = "$S_int_entry.8";
48 | my $S_int_lastchange = "$S_int_entry.9";
49 | my $S_int_InOctets = "$S_int_entry.10";
50 | my $S_int_OutOctets = "$S_int_entry.16";
51 | my $S_int_number = ".1.3.6.1.2.1.2.1.0";
52 |
53 | # SNMP Status Codes
54 | my %phy_dev_status = (
55 | 1 => 'normal',
56 | 2 => 'warning',
57 | 3 => 'critical',
58 | 4 => 'shutdown',
59 | 5 => 'not Present',
60 | 6 => 'not Functioning',
61 | );
62 | my %module_status_code = (
63 | 1 => 'unknown',
64 | 2 => 'ok',
65 | 3 => 'disabled',
66 | 4 => 'okButDiagFailed',
67 | 5 => 'boot',
68 | 6 => 'selfTest',
69 | 7 => 'failed',
70 | 8 => 'missing',
71 | 9 => 'mismatchWithParent',
72 | 10 => 'mismatchConfig',
73 | 11 => 'diagFailed',
74 | 12 => 'dormant',
75 | 13 => 'outOfServiceAdmin',
76 | 14 => 'outOfServiceEnvTemp',
77 | 15 => 'poweredDown',
78 | 16 => 'poweredUp',
79 | 17 => 'powerDenied',
80 | 18 => 'powerCycled',
81 | 19 => 'okButPowerOverWarning',
82 | 20 => 'okButPowerOverCritical',
83 | 21 => 'syncInProgress',
84 | );
85 | my %int_status_index = (
86 | 1 => 'up',
87 | 2 => 'down',
88 | 3 => 'testing',
89 | 4 => 'unknown',
90 | 5 => 'notPresent',
91 | 6 => 'lowerLayerDown',
92 | );
93 |
94 | ### Functions
95 | ###############
96 | sub check_oid_return {
97 | my ($oid_value, $parameter_name) = @_;
98 |
99 | if ( $oid_value == '' ) {
100 | print "Remote device does not return data for $parameter_name\n";
101 | exit(1);
102 | }
103 | }
104 |
105 | sub _create_session {
106 | my ($server, $comm) = @_;
107 | my $version = 1;
108 | my ($sess, $err) = Net::SNMP->session( -hostname => $server, -version => $version, -community => $comm);
109 |
110 | return $sess;
111 | }
112 |
113 | sub FSyntaxError {
114 | print "Syntax Error !\n";
115 | # print "$0 -H [ip|dnsname] -C [snmp community] -t [temp|fan|ps|cpu|mem|module|freeint] -w [warning value] -c [critical value] -d [days]\n";
116 | print "$script_name\n";
117 | print "-H = Ip/Dns Name of the Switch\n";
118 | print "-C = SNMP Community\n";
119 | print "-t = Check type\n";
120 | print "\ttemp - Temperature\n";
121 | print "\tfan - Fan Fail\n";
122 | print "\tps - Power Supply Fail\n";
123 | print "\tcpu - CPU Load\n";
124 | print "\tmem - Memory\n";
125 | print "\tmodule - Module Health\n";
126 | print "\tfreeint - Free eth interfaces for X days (-d)\n";
127 | print "\tint - Interface Operation Stat (use with -i or -o)\n";
128 | print "-w = Warning Value\n";
129 | print "-c = Critical Value\n";
130 | print "-d = number of days that the ethernet interface hasn't change state, default is 14 (only for -t freeint)\n";
131 | print "-i = Interface Name (only for -t int)\n";
132 | print "-o = Interface OID (only for -t int)\n";
133 | exit(3);
134 | }
135 |
136 | if($#ARGV < 5 or $#ARGV > 11) {
137 | FSyntaxError;
138 | }
139 |
140 | ### Gather input from user
141 | #############################
142 | my $switch;
143 | my $community;
144 | my $check_type;
145 | my $warn = 0;
146 | my $crit = 0;
147 | my $int;
148 | my $oidint;
149 |
150 | while(@ARGV) {
151 | my $temp = shift(@ARGV);
152 | if("$temp" eq '-H') {
153 | $switch = shift(@ARGV);
154 | } elsif("$temp" eq '-C') {
155 | $community = shift(@ARGV);
156 | } elsif("$temp" eq '-t') {
157 | $check_type = shift(@ARGV);
158 | } elsif("$temp" eq '-w') {
159 | $warn = shift(@ARGV);
160 | } elsif("$temp" eq '-c') {
161 | $crit = shift(@ARGV);
162 | } elsif("$temp" eq '-i') {
163 | $int = shift(@ARGV);
164 | } elsif("$temp" eq '-o') {
165 | $oidint = shift(@ARGV);
166 | } elsif("$temp" eq '-d') {
167 | $days = shift(@ARGV);
168 | if("$days" eq "") {
169 | $days = 14;
170 | }
171 | } else {
172 | FSyntaxError();
173 | }
174 | }
175 |
176 | # Validate Warning
177 | if("$check_type" ne "temp") {
178 | if($warn > $crit and "$check_type" ne "freeint" and "$check_type" ne "mem") {
179 | print "Warning can't be larger then Critical: $warn > $crit\n";
180 | FSyntaxError();
181 | } elsif($warn < $crit and "$check_type" eq "freeint") {
182 | print "Warning can't be smaller then Critical: $warn < $crit in intfree check\n";
183 | FSyntaxError();
184 | } elsif($warn < $crit and "$check_type" eq "mem") {
185 | print "Warning can't be smaller then Critical: $warn < $crit in intfree check\n";
186 | FSyntaxError();
187 | }
188 | }
189 |
190 | # Establish SNMP Session
191 | our $snmp_session = _create_session($switch,$community);
192 |
193 | ### Temperature ###
194 | if($check_type =~ /^temp/) {
195 | my $temp;
196 | my $R_tbl = $snmp_session->get_table($S_temp);
197 | if (!defined $R_tbl) {
198 | printf "SNMP error: %s\n", $snmp_session->error();
199 | exit(2);
200 | }
201 |
202 | foreach my $oid ( keys %$R_tbl) {
203 | $temp = "$$R_tbl{$oid}";
204 | last;
205 | }
206 |
207 | check_oid_return($temp, $check_type);
208 |
209 | if($temp > 1) {
210 | if($warn > $crit and "$check_type") {
211 | print "Warning can't be larger then Critical: $warn > $crit\n";
212 | FSyntaxError();
213 | }
214 | if($temp <= $warn) {
215 | $stat = 0;
216 | $msg = "Temperature: OK - Temperature is $temp Celsius";
217 | } elsif($temp > $warn and $temp < $crit) {
218 | $stat = 1;
219 | $msg = "Temperature: Warn - Temperature is $temp Celsius";
220 | } elsif($temp >= $crit) {
221 | $stat = 2;
222 | $msg = "Temperature: CRIT - Temperature is $temp Celsius";
223 | }
224 | $perf = "temperature=$temp;$warn;$crit";
225 | } else {
226 | if($warn > 0 or $crit > 0) {
227 | print "ERR:\nSome switches only show boolean value 0=OK 1=ERROR\nplease dont use -w and -c arguments\n\n";
228 | FSyntaxError();
229 | }
230 | if($temp == 1) {
231 | $stat = 0;
232 | $msg = "Temperature: OK";
233 | } else {
234 | $stat = 2;
235 | $msg = "Temperature: CRIT";
236 | }
237 | $perf = "temperature=$temp";
238 | }
239 |
240 | ### Memory ###
241 |
242 | } elsif($check_type eq "mem") {
243 | my $R_mem_used = $snmp_session->get_request(-varbindlist => [$S_mem_used]);
244 | if (!defined $R_mem_used) {
245 | printf "SNMP error: %s\n", $snmp_session->error();
246 | exit(2);
247 | }
248 |
249 | my $mem_used = "$R_mem_used->{$S_mem_used}";
250 | my $R_mem_free = $snmp_session->get_request(-varbindlist => [$S_mem_free]);
251 | if (!defined $R_mem_free) {
252 | printf "SNMP error: %s\n", $snmp_session->error();
253 | exit(2);
254 | }
255 | my $mem_free = "$R_mem_free->{$S_mem_free}";
256 | my $mem_total = $mem_free + $mem_used;
257 |
258 |
259 | check_oid_return($mem_used, $check_type);
260 | check_oid_return($mem_free, $check_type);
261 |
262 |
263 | $mem_used = int($mem_used / 1024 / 1024);
264 | $mem_free = int($mem_free / 1024 / 1024);
265 | $mem_total = int($mem_total / 1024 / 1024);
266 |
267 |
268 | my $mem_free_perc = int($mem_free / $mem_total * 100);
269 |
270 | if($mem_free_perc > $warn) {
271 | $stat = 0;
272 | $msg = "Memory: OK - Free Memory $mem_free_perc%";
273 | } elsif($mem_free_perc <= $warn and $mem_free_perc > $crit) {
274 | $stat = 1;
275 | $msg = "Memory: Warn - Free Memory $mem_free_perc %";
276 | } elsif($mem_free_perc <= $crit) {
277 | $stat = 2;
278 | $msg = "Memory: CRIT - Free Memory $mem_free_perc %";
279 | }
280 |
281 | $perf = "memory_total=$mem_total\MB memory_used=$mem_used\MB";
282 |
283 | ### Interface Stat ###
284 |
285 | } elsif($check_type eq "int") {
286 | my $R_tbl;
287 | if ($oidint) {
288 | $R_tbl = $snmp_session->get_request(-varbindlist => ["$oidint"]);
289 | if (!defined $R_tbl) {
290 | printf "SNMP error: %s\n", $snmp_session->error();
291 | exit(2);
292 | }
293 | $int = $$R_tbl{"$oidint"};
294 | } else {
295 | $R_tbl = $snmp_session->get_table($S_int_desc);
296 | if (!defined $R_tbl) {
297 | printf "SNMP error: %s\n", $snmp_session->error();
298 | exit(2);
299 | }
300 | }
301 | my $is_int_exists = 0;
302 | foreach my $oid ( keys %$R_tbl) {
303 | my $name = "$$R_tbl{$oid}";
304 | if($name eq $int) {
305 | $is_int_exists++;
306 | my $id = "$oid";
307 | $id =~ s/$S_int_desc\.//;
308 | my $R_stat = $snmp_session->get_request(-varbindlist => ["$S_int_operstatus.$id"]);
309 | if (!defined $R_stat) {
310 | printf "SNMP error: %s\n", $snmp_session->error();
311 | exit(2);
312 | }
313 | my $int_stat = $R_stat->{"$S_int_operstatus.$id"};
314 | if($int_stat != 1) {
315 | $stat = 2;
316 | $msg = "CRIT: $int -> $int_status_index{$int_stat}";
317 | $perf = "int=0";
318 | } else {
319 | $stat = 0;
320 | $msg = "OK: $int -> $int_status_index{$int_stat}";
321 | $perf = "int=1";
322 | }
323 | last;
324 | }
325 |
326 | }
327 |
328 | if($is_int_exists == 0) {
329 | $stat = 3;
330 | $msg = "UNKNOWN: $int does not exists";
331 | $perf = "int=0";
332 | }
333 |
334 | ### CPU Load ###
335 |
336 | } elsif($check_type eq "cpu") {
337 | my $R_load_5s = $snmp_session->get_request(-varbindlist => [$S_load_5s]);
338 | if (!defined $R_load_5s) {
339 | printf "SNMP error: %s\n", $snmp_session->error();
340 | exit(2);
341 | }
342 | my $load_5s = "$R_load_5s->{$S_load_5s}";
343 | my $R_load_1m = $snmp_session->get_request(-varbindlist => [$S_load_1m]);
344 | if (!defined $R_load_1m) {
345 | printf "SNMP error: %s\n", $snmp_session->error();
346 | exit(2);
347 | }
348 | my $load_1m = "$R_load_1m->{$S_load_1m}";
349 | my $R_load_5m = $snmp_session->get_request(-varbindlist => [$S_load_5m]);
350 | if (!defined $R_load_5m) {
351 | printf "SNMP error: %s\n", $snmp_session->error();
352 | exit(2);
353 | }
354 | my $load_5m = "$R_load_5m->{$S_load_5m}";
355 |
356 | check_oid_return($load_5s, $check_type);
357 | check_oid_return($load_1m, $check_type);
358 | check_oid_return($load_5m, $check_type);
359 |
360 | if($load_5s <= $warn) {
361 | $stat = 0;
362 | $msg = "Cpu: OK - Cpu Load $load_5s% $load_1m% $load_5m%";
363 | } elsif($load_5s > $warn and $load_5s < $crit) {
364 | $stat = 1;
365 | $msg = "Cpu: Warn - Cpu Load $load_5s% $load_1m% $load_5m%";
366 | } elsif($load_5s >= $crit) {
367 | $stat = 2;
368 | $msg = "Cpu: CRIT - Cpu Load $load_5s% $load_1m% $load_5m%";
369 | }
370 |
371 | $perf = "cpu_5s=$load_5s\percent;$warn;$crit cpu_1m=$load_1m\percent cpu_5m=$load_5m\percent";
372 |
373 | ### Fan Status ###
374 |
375 | } elsif($check_type eq "fan") {
376 | my $R_tbl = $snmp_session->get_table($S_fan_name);
377 | if (!defined $R_tbl) {
378 | printf "SNMP error: %s\n", $snmp_session->error();
379 | exit(2);
380 | }
381 | my $total_err = 0;
382 | my $err_msg;
383 | my $sum = 0;
384 | foreach my $oid ( keys %$R_tbl) {
385 | $sum = $sum + 1;
386 | my $name = "$$R_tbl{$oid}";
387 | my $id = "$oid";
388 | $id =~ s/$S_fan_name\.//;
389 | my $R_stat = $snmp_session->get_request(-varbindlist => ["$S_fan_stat.$id"]);
390 | if (!defined $R_stat) {
391 | printf "SNMP error: %s\n", $snmp_session->error();
392 | exit(2);
393 | }
394 | my $stat = $R_stat->{"$S_fan_stat.$id"};
395 | if($stat != 1) {
396 | $total_err = $total_err + 1;
397 | $err_msg = "$err_msg $name -> $phy_dev_status{$stat}";
398 | }
399 | }
400 |
401 | if($sum == 0) {
402 | print "fan: CRIT - No Fans are running\n";
403 | exit(1);
404 | }
405 |
406 | if($total_err != 0) {
407 | $err_msg = ", $err_msg have an error";
408 | } else {
409 | $err_msg = "all good";
410 | }
411 |
412 | if($total_err <= $warn) {
413 | $stat = 0;
414 | $msg = "Fans: OK - $sum Fans are running $err_msg";
415 | } elsif($total_err > $warn and $total_err < $crit) {
416 | $stat = 1;
417 | $msg = "Fans: Warn - $sum Fans are running $err_msg";
418 | } elsif($total_err >= $crit) {
419 | $stat = 2;
420 | $msg = "Fans: Crit - $sum Fans are running $err_msg";
421 | }
422 |
423 | $perf = "total=$sum err=$total_err";
424 |
425 | ### Power Supplies ###
426 |
427 | } elsif($check_type eq "ps") {
428 | my $R_tbl = $snmp_session->get_table($S_ps_name);
429 | if (!defined $R_tbl) {
430 | printf "SNMP error: %s\n", $snmp_session->error();
431 | exit(2);
432 | }
433 |
434 | my $total_err = 0;
435 | my $err_msg;
436 | my $sum = 0;
437 | foreach my $oid ( keys %$R_tbl) {
438 | $sum = $sum + 1;
439 | my $name = "$$R_tbl{$oid}";
440 | my $id = "$oid";
441 | $id =~ s/$S_ps_name\.//;
442 | my $R_stat = $snmp_session->get_request(-varbindlist => ["$S_ps_stat.$id"]);
443 | if (!defined $R_stat) {
444 | printf "SNMP error: %s\n", $snmp_session->error();
445 | exit(2);
446 | }
447 |
448 | my $stat = $R_stat->{"$S_ps_stat.$id"};
449 | if($stat != 1) {
450 | $total_err = $total_err + 1;
451 | $err_msg = "$err_msg $name -> $phy_dev_status{$stat}";
452 | }
453 | }
454 |
455 | if($total_err != 0) {
456 | $err_msg = ", $err_msg have an error";
457 | } else {
458 | $err_msg = "all good";
459 | }
460 |
461 | if($total_err <= $warn) {
462 | $stat = 0;
463 | $msg = "PS: OK - $sum PS are running $err_msg";
464 | } elsif($total_err > $warn and $total_err < $crit) {
465 | $stat = 1;
466 | $msg = "PS: Warn - $sum PS are running $err_msg";
467 | } elsif($total_err >= $crit) {
468 | $stat = 2;
469 | $msg = "PS: Crit - $sum PS are running $err_msg";
470 | }
471 |
472 | $perf = "total=$sum err=$total_err";
473 |
474 | ### Module Status ###
475 |
476 | } elsif($check_type eq "module") {
477 | my $R_tbl = $snmp_session->get_table($S_module_status);
478 | if (!defined $R_tbl) {
479 | printf "SNMP error: %s\n", $snmp_session->error();
480 | exit(2);
481 | }
482 | my $total_err = 0;
483 | my $err_msg;
484 | my $sum = 0;
485 | foreach my $oid ( keys %$R_tbl) {
486 | $sum = $sum + 1;
487 | my $module_status = "$$R_tbl{$oid}";
488 | my $id = "$oid";
489 | $id =~ s/$S_module_status\.//;
490 | if($module_status != 2) {
491 | $total_err = $total_err + 1;
492 | $err_msg = "$err_msg $id -> $module_status_code{$module_status}";
493 | }
494 | }
495 |
496 | if($sum == 0) {
497 | print "The switch $switch doesn't have any modules\n";
498 | FSyntaxError();
499 | }
500 |
501 | if($total_err != 0) {
502 | $err_msg = ", $err_msg have an error";
503 | } else {
504 | $err_msg = "all good";
505 | }
506 |
507 | if($total_err <= $warn) {
508 | $stat = 0;
509 | $msg = "Modules: OK - $sum Modules are running $err_msg";
510 | } elsif($total_err > $warn and $total_err < $crit) {
511 | $stat = 1;
512 | $msg = "Modules: Warn - $sum Modules are running $err_msg";
513 | } elsif($total_err >= $crit) {
514 | $stat = 2;
515 | $msg = "Modules: Crit - $sum Modules are running $err_msg";
516 | }
517 |
518 | $perf = "total=$sum err=$total_err";
519 |
520 | ### Free Interfaces ###
521 |
522 | } elsif($check_type eq "freeint") {
523 |
524 | my $R_int_number = $snmp_session->get_request(-varbindlist => [$S_int_number]);
525 | if (!defined $R_int_number) {
526 | printf "SNMP error: %s\n", $snmp_session->error();
527 | exit(2);
528 | }
529 | my $int_number = $R_int_number->{$S_int_number};
530 |
531 | my $R_tbl = $snmp_session->get_table($S_int_desc);
532 | if (!defined $R_tbl) {
533 | printf "SNMP error: %s\n", $snmp_session->error();
534 | exit(2);
535 | }
536 | my @ints;
537 | my $down = 0;
538 | my $sum = 0;
539 |
540 | foreach my $oid ( keys %$R_tbl) {
541 | if($$R_tbl{$oid} =~ /Ethernet/) {
542 | $sum++;
543 | my $id = "$oid";
544 | $id =~ s/$S_int_desc\.//;
545 |
546 | # Admin Status
547 | my $R_int_adminstatus = $snmp_session->get_request(-varbindlist => ["$S_int_adminstatus.$id"]);
548 | if (!defined $R_int_adminstatus) {
549 | printf "SNMP error: %s\n", $snmp_session->error();
550 | exit(2);
551 | }
552 | my $int_adminstatus = $R_int_adminstatus->{"$S_int_adminstatus.$id"};
553 | # Oper Status
554 | my $R_int_operstatus = $snmp_session->get_request(-varbindlist => ["$S_int_operstatus.$id"]);
555 | if (!defined $R_int_operstatus) {
556 | printf "SNMP error: %s\n", $snmp_session->error();
557 | exit(2);
558 | }
559 | my $int_operstatus = $R_int_operstatus->{"$S_int_operstatus.$id"};
560 | # Inbout
561 | my $R_int_InOctets = $snmp_session->get_request(-varbindlist => ["$S_int_InOctets.$id"]);
562 | if (!defined $R_int_InOctets) {
563 | printf "SNMP error: %s\n", $snmp_session->error();
564 | exit(2);
565 | }
566 | my $int_InOctets = $R_int_InOctets->{"$S_int_InOctets.$id"};
567 | # Outbound
568 | my $R_int_OutOctets = $snmp_session->get_request(-varbindlist => ["$S_int_OutOctets.$id"]);
569 | if (!defined $R_int_OutOctets) {
570 | printf "SNMP error: %s\n", $snmp_session->error();
571 | exit(2);
572 | }
573 | my $int_OutOctets = $R_int_OutOctets->{"$S_int_OutOctets.$id"};
574 | # Last Change
575 | my $R_int_lastchange = $snmp_session->get_request(-varbindlist => ["$S_int_lastchange.$id"]);
576 | if (!defined $R_int_lastchange) {
577 | printf "SNMP error: %s\n", $snmp_session->error();
578 | exit(2);
579 | }
580 | my $int_lastchange = $R_int_lastchange->{"$S_int_lastchange.$id"};
581 | my @lastchanged = split(" ",$int_lastchange);
582 |
583 | if($int_adminstatus == 2 or $int_operstatus == 2) {
584 | if(("$lastchanged[1]" eq "days," and $lastchanged[1] => $days) or ($int_OutOctets == 0 and $int_InOctets == 0)) {
585 | $down++;
586 | }
587 | }
588 |
589 | }
590 | }
591 |
592 | if($down >= $warn) {
593 | $stat = 0;
594 | $msg = "Free Interfaces: OK - $down/$sum free interfaces for $days days";
595 | } elsif($down < $warn and $down > $crit) {
596 | $stat = 1;
597 | $msg = "Free Interfaces: Warn - $down/$sum free interfaces for $days days";
598 | } elsif($down <= $crit) {
599 | $stat = 2;
600 | $msg = "Free Interfaces: CRIT - $down/$sum free interfaces for $days days";
601 | }
602 |
603 | $perf = "total_int=$int_number total_eth=$sum total_eth_free=$down";
604 |
605 | ### Bad Syntax ###
606 |
607 | } else {
608 | FSyntaxError();
609 | }
610 |
611 |
612 | print "$msg | $perf\n";
613 | exit($stat);
614 |
--------------------------------------------------------------------------------
/nagios/check-file-exists.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/perl
2 |
3 | # Modules
4 | use strict;
5 | use Getopt::Long;
6 | Getopt::Long::Configure('bundling');
7 |
8 | # Functions
9 | sub _syntax_err(@)
10 | {
11 | my $msg = shift;
12 | print <= than -c") if ($opt{'warn'} >= $opt{'crit'});
44 |
45 | # Variables
46 | my $OK = 0;
47 | my $WARNING = 1;
48 | my $CRITICAL = 2;
49 | my $UNKNOWN = 3;
50 | my $status = $OK;
51 | my $msg;
52 | my $perf;
53 |
54 | # Take mtime and systems's epoc if file exists
55 | if( -f $opt{'file'})
56 | {
57 | my $filestat = (stat($opt{'file'}))[9];
58 | my $epoc = time;
59 | my $timediff = $epoc - $filestat;
60 | my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
61 | $year += 1900;
62 | $mon += 1;
63 | my $timestamp = "$mday/$mon/$year $hour:$min:$sec";
64 |
65 | # Decide exit status
66 | if ($timediff < $opt{'warn'})
67 | {
68 | $msg = "OK: look's good";
69 | $status = $OK;
70 | }
71 | elsif ($timediff >= $opt{'warn'} && $timediff < $opt{'crit'})
72 | {
73 | $msg = "WARN: $opt{'file'} mtime is $timestamp";
74 | $status = $WARNING;
75 | }
76 | else
77 | {
78 | $msg = "CRIT: $opt{'file'} mtime is $timestamp";
79 | $status = $CRITICAL;
80 | }
81 |
82 | $perf = "mtime=$timediff"."s".";$opt{'warn'};$opt{'crit'}";
83 | }
84 | # If file doesn't exists exit OK nothing to check (or UNKNOWN in case of -v)
85 | else
86 | {
87 | if($opt{'verify'})
88 | {
89 | $msg = "UNKNOWN: $opt{'file'} doesn't exists";
90 | $perf = "mtime=0s;$opt{'warn'};$opt{'crit'}";
91 | $status = $UNKNOWN;
92 | }
93 | else
94 | {
95 | $msg = "OK: $opt{'file'} doesn't exists, nothing to check";
96 | $perf = "mtime=0s;$opt{'warn'};$opt{'crit'}";
97 | $status = $OK;
98 | }
99 | }
100 |
101 | # Exit
102 | print "$msg | $perf\n";
103 | exit($status);
104 |
--------------------------------------------------------------------------------
/nagios/check-juniper-vpn.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | use strict;
15 | use lib "/path/to/nagios/libexec";
16 | use utils qw($TIMEOUT %ERRORS);
17 | use Net::SNMP;
18 | use Getopt::Long;
19 | Getopt::Long::Configure('bundling');
20 |
21 | my $stat = 0;
22 | my $msg;
23 | my $perf;
24 | my $script_name = "check-juniper-vpn.pl";
25 |
26 | ### SNMP OIDs
27 | ###############
28 | # IVE
29 | my $snmp_juniper_ive = '.1.3.6.1.4.1.12532';
30 | my $snmp_juniper_logFullPercent = "$snmp_juniper_ive.1.0";
31 | my $snmp_juniper_WebUsers = "$snmp_juniper_ive.2.0";
32 | my $snmp_juniper_MailUsers = "$snmp_juniper_ive.3.0";
33 | my $snmp_juniper_MeetingUsers = "$snmp_juniper_ive.9.0";
34 | my $snmp_juniper_iveCpuUtil = "$snmp_juniper_ive.10.0";
35 | my $snmp_juniper_iveMemoryUtil = "$snmp_juniper_ive.11.0";
36 | my $snmp_juniper_iveConcurrentUsers = "$snmp_juniper_ive.12.0";
37 | my $snmp_juniper_MeetingCount = "$snmp_juniper_ive.22.0";
38 | my $snmp_juniper_iveSwapUtil = "$snmp_juniper_ive.24.0";
39 | my $snmp_juniper_fanDescription = "$snmp_juniper_ive.32.0";
40 | my $snmp_juniper_psDescription = "$snmp_juniper_ive.33.0";
41 | my $snmp_juniper_raidDescription = "$snmp_juniper_ive.34.0";
42 |
43 | my $snmp_juniper_ucdavis = '.1.3.6.1.4.1.2021';
44 | # Memory
45 | my $snmp_juniper_Memory = "$snmp_juniper_ucdavis.4";
46 | my $snmp_juniper_Memory_TotalSwap = "$snmp_juniper_Memory.3.0";
47 | my $snmp_juniper_Memory_AvailSwap = "$snmp_juniper_Memory.4.0";
48 | my $snmp_juniper_Memory_TotalMem = "$snmp_juniper_Memory.5.0";
49 | my $snmp_juniper_Memory_AvailMem = "$snmp_juniper_Memory.6.0";
50 | my $snmp_juniper_Memory_TotalFree = "$snmp_juniper_Memory.11.0";
51 | my $snmp_juniper_Memory_Shared = "$snmp_juniper_Memory.13.0";
52 | my $snmp_juniper_Memory_Buffer = "$snmp_juniper_Memory.14.0";
53 | my $snmp_juniper_Memory_Cached = "$snmp_juniper_Memory.15.0";
54 | # Disk
55 | my $snmp_juniper_Disk = "$snmp_juniper_ucdavis.9.1";
56 | my $snmp_juniper_Disk_Index = "$snmp_juniper_Disk.1";
57 | my $snmp_juniper_Disk_Total = "$snmp_juniper_Disk.6.1";
58 | my $snmp_juniper_Disk_Avail = "$snmp_juniper_Disk.7.1";
59 | my $snmp_juniper_Disk_Used = "$snmp_juniper_Disk.8.1";
60 | my $snmp_juniper_Disk_Used_Percent = "$snmp_juniper_Disk.9.1";
61 | # Load
62 | my $snmp_juniper_Load = "$snmp_juniper_ucdavis.10.1";
63 | my $snmp_juniper_Load_Index = "$snmp_juniper_Load.1";
64 | my $snmp_juniper_Load_Load = "$snmp_juniper_Load.3";
65 | my $snmp_juniper_Load_Load_1 = "$snmp_juniper_Load_Load.1";
66 | my $snmp_juniper_Load_Load_5 = "$snmp_juniper_Load_Load.2";
67 | my $snmp_juniper_Load_Load_15 = "$snmp_juniper_Load_Load.3";
68 |
69 |
70 |
71 | ### Functions
72 | ###############
73 | sub _create_session(@) {
74 | my ($server, $comm) = @_;
75 | my $version = 1;
76 | my ($sess, $err) = Net::SNMP->session( -hostname => $server, -version => $version, -community => $comm);
77 | if (!defined($sess)) {
78 | print "Can't create SNMP session to $server\n";
79 | exit(1);
80 | }
81 | return $sess;
82 | }
83 |
84 | sub FSyntaxError($) {
85 | my $err = shift;
86 | print <get_request(-varbindlist => [$local_oid]);
116 | return($r_return->{$local_oid});
117 | }
118 |
119 | sub _clac_err_stat(@) {
120 | my $value = shift;
121 | my $value_type = shift;
122 | my $tmp_warn = shift;
123 | my $tmp_crit = shift;
124 | my $unit = shift;
125 | my $r_msg;
126 | my $r_stat;
127 | if($value <= $tmp_warn) {
128 | $r_stat = $ERRORS{'OK'};
129 | $r_msg = "OK: $value_type $value$unit";
130 | } elsif($value > $tmp_warn and $value < $tmp_crit) {
131 | $r_stat = $ERRORS{'WARNING'};
132 | $r_msg = "WARN: $value_type $value$unit";
133 | } elsif($value >= $tmp_crit) {
134 | $r_stat = $ERRORS{'CRITICAL'};
135 | $r_msg = "CRIT: $value_type $value$unit";
136 | }
137 | return($r_msg,$r_stat);
138 | }
139 |
140 | ### Gather input from user
141 | #############################
142 | my %opt;
143 | $opt{'crit'} = 500;
144 | $opt{'warn'} = 500;
145 | my $result = GetOptions(\%opt,
146 | 'host|H=s',
147 | 'community|C=s',
148 | 'check_type|T=s',
149 | 'warn|w=f',
150 | 'crit|c=f',
151 | );
152 |
153 | FSyntaxError("Missing -H") unless defined $opt{'host'};
154 | FSyntaxError("Missing -C") unless defined $opt{'community'};
155 | FSyntaxError("Missing -T") unless defined $opt{'check_type'};
156 | if($opt{'warn'} > $opt{'crit'}) {
157 | FSyntaxError("Warning can't be larger then Critical: $opt{'warn'} > $opt{'crit'}");
158 | }
159 |
160 | # Starting Alaram
161 | alarm($TIMEOUT);
162 |
163 | # Establish SNMP Session
164 | our $snmp_session = _create_session($opt{'host'},$opt{'community'});
165 |
166 | ### LOG ###
167 | if("$opt{'check_type'}" eq "LOG") {
168 | my $check = _get_oid_value($snmp_session,$snmp_juniper_logFullPercent);
169 | ($msg,$stat) = _clac_err_stat($check,$opt{'check_type'},$opt{'warn'},$opt{'crit'},'%');
170 | $perf = "logsize=$check\%";
171 | ### Users ###
172 | } elsif("$opt{'check_type'}" eq "USERS") {
173 | my $check = _get_oid_value($snmp_session,$snmp_juniper_iveConcurrentUsers);
174 | my $u_web = _get_oid_value($snmp_session,$snmp_juniper_WebUsers);
175 | my $u_mail = _get_oid_value($snmp_session,$snmp_juniper_MailUsers);
176 | my $u_meet = _get_oid_value($snmp_session,$snmp_juniper_MeetingUsers);
177 |
178 | unless($u_web) { $u_web = 0; }
179 | unless($u_mail) { $u_mail = 0; }
180 | unless($u_meet) { $u_meet = 0; }
181 |
182 | ($msg,$stat) = _clac_err_stat($check,$opt{'check_type'},$opt{'warn'},$opt{'crit'});
183 | $perf = "all_users=$check web_users=$u_web mail_users=$u_mail meeting_users=$u_meet";
184 | ### MEETINGS ###
185 | } elsif("$opt{'check_type'}" eq "MEETINGS") {
186 | my $check = _get_oid_value($snmp_session,$snmp_juniper_MeetingCount);
187 | unless($check) { $check = 0; }
188 | ($msg,$stat) = _clac_err_stat($check,$opt{'check_type'},$opt{'warn'},$opt{'crit'});
189 | $perf = "meetings=$check";
190 | ### CPULOAD ###
191 | } elsif("$opt{'check_type'}" eq "CPULOAD") {
192 | my $load1 = _get_oid_value($snmp_session,$snmp_juniper_Load_Load_1);
193 | my $load5 = _get_oid_value($snmp_session,$snmp_juniper_Load_Load_5);
194 | my $load15 = _get_oid_value($snmp_session,$snmp_juniper_Load_Load_15);
195 |
196 | ($msg,$stat) = _clac_err_stat($load1,$opt{'check_type'},$opt{'warn'},$opt{'crit'});
197 | $perf = "load1min=$load1 load5min=$load5 load15min=$load15";
198 | ### MEM ###
199 | } elsif("$opt{'check_type'}" eq "MEM") {
200 | my $r_mem_tbl = $snmp_session->get_table($snmp_juniper_Memory);
201 | my $Used_Mem = $$r_mem_tbl{$snmp_juniper_Memory_TotalMem} - $$r_mem_tbl{$snmp_juniper_Memory_AvailMem};
202 | my $Used_Percent = int(($Used_Mem / $$r_mem_tbl{$snmp_juniper_Memory_TotalMem}) * 100);
203 | ($msg,$stat) = _clac_err_stat($Used_Percent,$opt{'check_type'},$opt{'warn'},$opt{'crit'},'%');
204 | $perf = "total=$$r_mem_tbl{$snmp_juniper_Memory_TotalMem}\k used=$Used_Mem shared=$$r_mem_tbl{$snmp_juniper_Memory_Shared}\k buffer=$$r_mem_tbl{$snmp_juniper_Memory_Buffer}\k cached=$$r_mem_tbl{$snmp_juniper_Memory_Cached}\k";
205 | ### SWAP ###
206 | } elsif("$opt{'check_type'}" eq "SWAP") {
207 | my $r_mem_tbl = $snmp_session->get_table($snmp_juniper_Memory);
208 | my $Used_Mem = $$r_mem_tbl{$snmp_juniper_Memory_TotalSwap} - $$r_mem_tbl{$snmp_juniper_Memory_AvailSwap};
209 | my $Used_Percent = int(($Used_Mem / $$r_mem_tbl{$snmp_juniper_Memory_TotalSwap}) * 100);
210 | ($msg,$stat) = _clac_err_stat($Used_Percent,$opt{'check_type'},$opt{'warn'},$opt{'crit'},'%');
211 | $perf = "total=$$r_mem_tbl{$snmp_juniper_Memory_TotalSwap}\k used=$Used_Mem\k";
212 | ### DISK ###
213 | } elsif("$opt{'check_type'}" eq "DISK") {
214 | my $r_disk_tbl = $snmp_session->get_table($snmp_juniper_Disk);
215 | ($msg,$stat) = _clac_err_stat($$r_disk_tbl{$snmp_juniper_Disk_Used_Percent},$opt{'check_type'},$opt{'warn'},$opt{'crit'},'%');
216 | $perf = "total=$$r_disk_tbl{$snmp_juniper_Disk_Total} used=$$r_disk_tbl{$snmp_juniper_Disk_Used}";
217 | ### Syntax Error ###
218 | } else {
219 | FSyntaxError("$opt{'check_type'} invalid parameter !");
220 | }
221 |
222 |
223 | print "$msg | $perf\n";
224 | exit($stat);
225 |
226 |
--------------------------------------------------------------------------------
/nagios/check-paloalto-A500.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 | ## Original version written by
14 | ## ran.leibman@gmail.com
15 | ## Additionial checks code written
16 | ## by laurent.dufour@havas.com
17 | ##
18 | ## the following parameters has
19 | ## been tested against a PA5050
20 | ##
21 | ## cpu|firmware|ha|model|
22 | ## sessions|udp_sessions|tcp_sessions
23 | ## |icmp_sessions
24 | ##
25 | #####################################
26 | #####################################
27 |
28 |
29 | use strict;
30 | use lib "/usr/lib/nagios/plugins/";
31 | use Net::SNMP;
32 | my $stat;
33 | my $msg;
34 | my $perf;
35 | my $script_name = "check-paloalto-A500.pl";
36 | my $script_version = 1.1;
37 |
38 |
39 | ### SNMP OIDs
40 | ###############
41 | my $s_cpu_mgmt = '.1.3.6.1.2.1.25.3.3.1.2.1';
42 | my $s_cpu_data = '.1.3.6.1.2.1.25.3.3.1.2.2';
43 | my $s_firmware = '.1.3.6.1.2.1.25.3.3.1.2.2';
44 | my $s_firmware_version = '.1.3.6.1.4.1.25461.2.1.2.1.1.0';
45 | my $s_ha_mode = '.1.3.6.1.4.1.25461.2.1.2.1.13.0';
46 | my $s_ha_local_state = '.1.3.6.1.4.1.25461.2.1.2.1.11.0';
47 | my $s_ha_peer_state = '.1.3.6.1.4.1.25461.2.1.2.1.12.0';
48 | my $s_pa_model = '.1.3.6.1.4.1.25461.2.1.2.2.1.0';
49 | my $s_pa_max_sessions = '.1.3.6.1.4.1.25461.2.1.2.3.2.0';
50 | my $s_pa_total_active_sessions = '.1.3.6.1.4.1.25461.2.1.2.3.3.0';
51 | my $s_pa_total_tcp_active_sessions = '.1.3.6.1.4.1.25461.2.1.2.3.4.0';
52 | my $s_pa_total_udp_active_sessions = '.1.3.6.1.4.1.25461.2.1.2.3.5.0';
53 | my $s_pa_total_icmp_active_sessions = '.1.3.6.1.4.1.25461.2.1.2.3.6.0';
54 |
55 | ### Functions
56 | ###############
57 | sub _create_session {
58 | my ($server, $comm) = @_;
59 | my $snmp_version = 2;
60 | my ($sess, $err) = Net::SNMP->session( -hostname => $server, -version => $snmp_version, -community => $comm);
61 | if (!defined($sess)) {
62 | print "Can't create SNMP session to $server\n";
63 | exit(1);
64 | }
65 | return $sess;
66 | }
67 |
68 | sub FSyntaxError {
69 | print "Syntax Error !\n";
70 | # print "$0 -H [ip|dnsname] -C [snmp community] -t [temp|fan|ps|cpu|mem|module|freeint|firmware|ha|model|sessions|udp_sessions|tcp_sessions|icmp_sessions] -w [warning value] -c [critical value] -d [days]\n";
71 | print "$script_name\n";
72 | print "Version : $script_version\n";
73 | print "-H = Ip/Dns Name of the FW\n";
74 | print "-C = SNMP Community\n";
75 | print "-t = Check type (currently only cpu/firmware/model/ha/sessions/icmp_sessions/tcp_sessions/udp_sessions)\n";
76 | print "-w = Warning Value\n";
77 | print "-c = Critical Value\n";
78 | exit(3);
79 | }
80 |
81 | if($#ARGV != 9) {
82 | FSyntaxError;
83 | }
84 |
85 | ### Gather input from user
86 | #############################
87 | my $switch;
88 | my $community;
89 | my $check_type;
90 | my $warn = 0;
91 | my $crit = 0;
92 | my $int;
93 |
94 | while(@ARGV) {
95 | my $temp = shift(@ARGV);
96 | if("$temp" eq '-H') {
97 | $switch = shift(@ARGV);
98 | } elsif("$temp" eq '-C') {
99 | $community = shift(@ARGV);
100 | } elsif("$temp" eq '-t') {
101 | $check_type = shift(@ARGV);
102 | } elsif("$temp" eq '-w') {
103 | $warn = shift(@ARGV);
104 | } elsif("$temp" eq '-c') {
105 | $crit = shift(@ARGV);
106 | } else {
107 | FSyntaxError();
108 | }
109 | }
110 |
111 | # Validate Warning
112 | if($warn > $crit) {
113 | print "Warning can't be larger then Critical: $warn > $crit\n";
114 | FSyntaxError();
115 | }
116 |
117 | # Establish SNMP Session
118 | our $snmp_session = _create_session($switch,$community);
119 |
120 |
121 | ### model ###
122 | if($check_type eq "model") {
123 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_pa_model]);
124 | my $palo_model = "$R_firm->{$s_pa_model}";
125 |
126 | $msg = "OK: Palo Alto $palo_model";
127 | $perf="";
128 | $stat = 0;
129 | }
130 |
131 | ### HA MODE ###
132 | elsif($check_type eq "ha") {
133 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_ha_mode]);
134 | my $ha_mode = "$R_firm->{$s_ha_mode}";
135 |
136 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_ha_local_state]);
137 | my $ha_local_state = "$R_firm->{$s_ha_local_state}";
138 |
139 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_ha_peer_state]);
140 | my $ha_peer_state = "$R_firm->{$s_ha_peer_state}";
141 |
142 | $msg = "OK: High Availablity Mode: $ha_mode, Local: $ha_local_state, Peer: $ha_peer_state\n";
143 | $perf="";
144 | $stat = 0;
145 | }
146 |
147 |
148 | ### SESSIONS ###
149 | elsif($check_type eq "sessions") {
150 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_pa_max_sessions]);
151 | my $pa_max_sessions = "$R_firm->{$s_pa_max_sessions}";
152 |
153 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_pa_total_active_sessions]);
154 | my $pa_total_active_sessions = "$R_firm->{$s_pa_total_active_sessions}";
155 |
156 | $perf=" - Max Active Sessions : $pa_max_sessions";
157 |
158 | if($pa_total_active_sessions > $crit ) {
159 | $msg = "CRITICAL: Total Active Sessions: $pa_total_active_sessions".$perf;
160 | $stat = 2;
161 | } elsif($pa_total_active_sessions > $warn ) {
162 | $msg = "WARNING: Total Active Sessions: $pa_total_active_sessions".$perf;
163 | $stat = 1;
164 | } else {
165 | $msg = "OK: Total Active Sessions: $pa_total_active_sessions".$perf;
166 | $stat = 0;
167 | }
168 | $perf="";
169 | }
170 |
171 | ### TCP SESSIONS ###
172 | elsif($check_type eq "tcp_sessions") {
173 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_pa_total_tcp_active_sessions]);
174 | my $pa_total_tcp_active_sessions = "$R_firm->{$s_pa_total_tcp_active_sessions}";
175 |
176 | if($pa_total_tcp_active_sessions > $crit ) {
177 | $msg = "CRITICAL: TCP Active Sessions: $pa_total_tcp_active_sessions";
178 | $stat = 2;
179 | } elsif($pa_total_tcp_active_sessions > $warn ) {
180 | $msg = "WARNING: TCP Active Sessions: $pa_total_tcp_active_sessions";
181 | $stat = 1;
182 | } else {
183 | $msg = "OK: TCP Active Sessions: $pa_total_tcp_active_sessions";
184 | $stat = 0;
185 | }
186 | $perf="";
187 | }
188 |
189 | ### UDP SESSIONS ###
190 | elsif($check_type eq "udp_sessions") {
191 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_pa_total_udp_active_sessions]);
192 | my $pa_total_udp_active_sessions = "$R_firm->{$s_pa_total_udp_active_sessions}";
193 |
194 | if($pa_total_udp_active_sessions > $crit ) {
195 | $msg = "CRITICAL: UDP Active Sessions: $pa_total_udp_active_sessions";
196 | $stat = 2;
197 | } elsif($pa_total_udp_active_sessions > $warn ) {
198 | $msg = "WARNING: UDP Active Sessions: $pa_total_udp_active_sessions";
199 | $stat = 1;
200 | } else {
201 | $msg = "OK: UDP Active Sessions: $pa_total_udp_active_sessions";
202 | $stat = 0;
203 | }
204 | $perf="";
205 | }
206 |
207 | ### ICMP SESSIONS ###
208 | elsif($check_type eq "icmp_sessions") {
209 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_pa_total_icmp_active_sessions]);
210 | my $pa_total_icmp_active_sessions = "$R_firm->{$s_pa_total_icmp_active_sessions}";
211 |
212 |
213 | if($pa_total_icmp_active_sessions > $crit ) {
214 | $msg = "CRITICAL: ICMP Active Sessions: $pa_total_icmp_active_sessions";
215 | $stat = 2;
216 | } elsif($pa_total_icmp_active_sessions > $warn ) {
217 | $msg = "WARNING: ICMP Active Sessions: $pa_total_icmp_active_sessions";
218 | $stat = 1;
219 | } else {
220 | $msg = "OK: ICMP Active Sessions: $pa_total_icmp_active_sessions";
221 | $stat = 0;
222 |
223 | }
224 | $perf="";
225 | }
226 |
227 | ### firmware ###
228 | elsif($check_type eq "firmware") {
229 | my $R_firm = $snmp_session->get_request(-varbindlist => [$s_firmware_version]);
230 | my $palo_os_ver = "$R_firm->{$s_firmware_version}";
231 |
232 | $msg = "OK: Firmware $palo_os_ver";
233 | $perf="";
234 | $stat = 0;
235 | }
236 |
237 | ### CPU ###
238 | elsif($check_type eq "cpu") {
239 | my $R_mgmt = $snmp_session->get_request(-varbindlist => [$s_cpu_mgmt]);
240 | my $mgmt = "$R_mgmt->{$s_cpu_mgmt}";
241 | my $R_data = $snmp_session->get_request(-varbindlist => [$s_cpu_data]);
242 | my $data = "$R_data->{$s_cpu_data}";
243 |
244 | if($mgmt > $crit or $data > $crit) {
245 | $msg = "CRITICAL: Mgmt: $mgmt, Data: $data";
246 | $stat = 2;
247 | } elsif($mgmt > $warn or $data > $warn) {
248 | $msg = "WARNING: Mgmt: $mgmt, Data: $data";
249 | $stat = 1;
250 | } else {
251 | $msg = "OK: Mgmt: $mgmt, Data: $data";
252 | $stat = 0;
253 | }
254 | $perf = "mgmt=$mgmt;data=$data;$warn;$crit";
255 |
256 | ### Bad Syntax ###
257 |
258 | } else {
259 | FSyntaxError();
260 | }
261 |
262 | if ($perf eq "") {
263 | print "$msg\n";
264 | } else {
265 | print "$msg | $perf\n";
266 | }
267 |
268 | exit($stat);
269 |
--------------------------------------------------------------------------------
/nagios/check-pineapp.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | use strict;
15 | use lib "/path/to/nagios/libexec";
16 | use utils qw($TIMEOUT %ERRORS);
17 | use Net::SNMP;
18 | use Getopt::Long;
19 | Getopt::Long::Configure('bundling');
20 |
21 | my $stat = $ERRORS{'OK'};
22 | my $msg;
23 | my $perf;
24 | my $script_name = "check-pineapp.pl";
25 |
26 | ### SNMP OIDs
27 | ###############
28 | # CPULOAD
29 | my $snmp_pineapp_cpuload = '.1.3.6.1.4.1.19801.1.1.3';
30 | my $snmp_pineapp_cpuload_1min = "$snmp_pineapp_cpuload.1.0";
31 | my $snmp_pineapp_cpuload_5min = "$snmp_pineapp_cpuload.2.0";
32 | my $snmp_pineapp_cpuload_15min = "$snmp_pineapp_cpuload.3.0";
33 | # Services
34 | my $snmp_pineapp_services = '.1.3.6.1.4.1.19801.2.1';
35 | my $snmp_pineapp_services_smtp = "$snmp_pineapp_services.1.0";
36 | my $snmp_pineapp_services_pop3 = "$snmp_pineapp_services.2.0";
37 | my $snmp_pineapp_services_imap4 = "$snmp_pineapp_services.3.0";
38 | my $snmp_pineapp_services_av = '.1.3.6.1.4.1.19801.2.5.1.0';
39 | # Queue
40 | my $snmp_pineapp_queues = "$snmp_pineapp_services.10";
41 | my $snmp_pineapp_queues_in = "$snmp_pineapp_queues.1.0";
42 | my $snmp_pineapp_queues_out = "$snmp_pineapp_queues.2.0";
43 | my $snmp_pineapp_queues_high = "$snmp_pineapp_queues.3.1.0";
44 | my $snmp_pineapp_queues_normal = "$snmp_pineapp_queues.3.2.0";
45 | my $snmp_pineapp_queues_low = "$snmp_pineapp_queues.3.3.0";
46 | my $snmp_pineapp_queues_total = "$snmp_pineapp_queues.3.4.0";
47 | my $snmp_pineapp_averageProcessingTimePerMsg = ".1.3.6.1.4.1.19801.2.2.1.4.0";
48 | # Misc
49 | my $snmp_pineapp_storage = '.1.3.6.1.4.1.19801.1.4.0';
50 |
51 | ### Functions
52 | ###############
53 | sub _create_session(@) {
54 | my ($server, $comm) = @_;
55 | my $version = 1;
56 | my ($sess, $err) = Net::SNMP->session( -hostname => $server, -version => $version, -community => $comm);
57 | if (!defined($sess)) {
58 | print "Can't create SNMP session to $server\n";
59 | exit(1);
60 | }
61 | return $sess;
62 | }
63 |
64 | sub FSyntaxError($) {
65 | my $err = shift;
66 | print <get_request(-varbindlist => [$local_oid]);
90 | return($r_return->{$local_oid});
91 | }
92 |
93 | sub _clac_err_stat(@) {
94 | my $value = shift;
95 | my $value_type = shift;
96 | my $tmp_warn = shift;
97 | my $tmp_crit = shift;
98 | my $unit = shift;
99 | my $r_msg;
100 | my $r_stat;
101 | if($value <= $tmp_warn) {
102 | $r_stat = $ERRORS{'OK'};
103 | $r_msg = "OK: $value_type $value$unit";
104 | } elsif($value > $tmp_warn and $value < $tmp_crit) {
105 | $r_stat = $ERRORS{'WARNING'};
106 | $r_msg = "WARN: $value_type $value$unit";
107 | } elsif($value >= $tmp_crit) {
108 | $r_stat = $ERRORS{'CRITICAL'};
109 | $r_msg = "CRIT: $value_type $value$unit";
110 | }
111 | return($r_msg,$r_stat);
112 | }
113 |
114 | ### Gather input from user
115 | #############################
116 | my %opt;
117 | $opt{'crit'} = 500;
118 | $opt{'warn'} = 500;
119 | my $result = GetOptions(\%opt,
120 | 'host|H=s',
121 | 'community|C=s',
122 | 'check_type|T=s',
123 | 'warn|w=f',
124 | 'crit|c=f',
125 | );
126 |
127 | FSyntaxError("Missing -H") unless defined $opt{'host'};
128 | FSyntaxError("Missing -C") unless defined $opt{'community'};
129 | FSyntaxError("Missing -T") unless defined $opt{'check_type'};
130 | if($opt{'warn'} > $opt{'crit'}) {
131 | FSyntaxError("Warning can't be larger then Critical: $opt{'warn'} > $opt{'crit'}");
132 | }
133 |
134 | # Starting Alaram
135 | alarm($TIMEOUT);
136 |
137 | # Establish SNMP Session
138 | our $snmp_session = _create_session($opt{'host'},$opt{'community'});
139 |
140 | # Start Check !
141 | ### CPULOAD ###
142 | if("$opt{'check_type'}" eq "CPULOAD") {
143 | my $check = $snmp_session->get_table($snmp_pineapp_cpuload);
144 | ($msg,$stat) = _clac_err_stat($$check{$snmp_pineapp_cpuload_1min},$opt{'check_type'},$opt{'warn'},$opt{'crit'});
145 | $perf = "load1=$$check{$snmp_pineapp_cpuload_1min} load5=$$check{$snmp_pineapp_cpuload_5min} load15=$$check{$snmp_pineapp_cpuload_15min}";
146 | ### SERVICES ###
147 | } elsif("$opt{'check_type'}" eq "SERVICES") {
148 | my %check = (
149 | 'smtp' => _get_oid_value($snmp_session,$snmp_pineapp_services_smtp),
150 | 'pop3' => _get_oid_value($snmp_session,$snmp_pineapp_services_pop3),
151 | 'imap4' => _get_oid_value($snmp_session,$snmp_pineapp_services_imap4),
152 | 'av' => _get_oid_value($snmp_session,$snmp_pineapp_services_av)
153 | );
154 |
155 | my $count = 0;
156 | foreach my $srv ( keys %check) {
157 | if($check{$srv} == 0 ){
158 | $msg = "$msg, $srv is down";
159 | $stat = $ERRORS{'CRITICAL'};
160 | $count++;
161 | }
162 | }
163 |
164 | if($count == 0) {
165 | $msg = "OK: All Services Ok !";
166 | } else {
167 | $msg = "CRIT: $msg";
168 | }
169 |
170 | $perf = "down_srv=$count";
171 | ### DISK ###
172 | } elsif("$opt{'check_type'}" eq "DISK") {
173 | my $check = _get_oid_value($snmp_session,$snmp_pineapp_storage);
174 | if($check eq "OK") {
175 | $stat = $ERRORS{'OK'};
176 | $msg = "OK: $opt{'check_type'} $check";
177 | $perf = "disk_err=0";
178 | } else {
179 | $stat = $ERRORS{'CRITICAL'};
180 | $msg = "CRIT: $opt{'check_type'} $check";
181 | $perf = "disk_err=1";
182 | }
183 | ### MSGPERSEC ###
184 | } elsif("$opt{'check_type'}" eq "MSGPERSEC") {
185 | my $check = _get_oid_value($snmp_session,$snmp_pineapp_averageProcessingTimePerMsg);
186 | ($msg,$stat) = _clac_err_stat($check,$opt{'check_type'},$opt{'warn'},$opt{'crit'},"sec");
187 | $perf = "msgPersec=$check\sec";
188 | ### INOUT ###
189 | } elsif("$opt{'check_type'}" eq "INOUT") {
190 | my $in = _get_oid_value($snmp_session,$snmp_pineapp_queues_in);
191 | my $out = _get_oid_value($snmp_session,$snmp_pineapp_queues_out);
192 | $msg = "OK: $opt{'check_type'} (Preformance Only)";
193 | $perf = "in=$in\msg out=-$out\msg";
194 | ### QUEUE ###
195 | } elsif("$opt{'check_type'}" eq "QUEUE") {
196 | my $high = _get_oid_value($snmp_session,$snmp_pineapp_queues_high);
197 | my $normal = _get_oid_value($snmp_session,$snmp_pineapp_queues_normal);
198 | my $low = _get_oid_value($snmp_session,$snmp_pineapp_queues_low);
199 | my $total = _get_oid_value($snmp_session,$snmp_pineapp_queues_total);
200 | ($msg,$stat) = _clac_err_stat($total,$opt{'check_type'},$opt{'warn'},$opt{'crit'},"msg");
201 | $perf = "total=$total\msg low=$low\msg normal=$normal\msg high=$high\msg";
202 | } else {
203 | FSyntaxError("$opt{'check_type'} invalid parameter !");
204 | }
205 |
206 |
207 | print "$msg | $perf\n";
208 | exit($stat);
209 |
--------------------------------------------------------------------------------
/nagios/check-roomalert.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | # Info
15 | # Checks AVTECH Room alert devices tempeture via SNMP
16 |
17 | use strict;
18 | use Net::SNMP;
19 | use Getopt::Long; Getopt::Long::Configure('bundling');
20 |
21 | my $stat = 0;
22 | my $msg = "RoomAlert";
23 | my $perf;
24 | my $script_name = "check-roomalert.pl";
25 |
26 | ### SNMP OIDs
27 | ###############
28 | my $s_internal = '.1.3.6.1.4.1.20916.1.6.1.1.1.2.0';
29 | my $s_external = '.1.3.6.1.4.1.20916.1.6.1.2.1.1.0';
30 |
31 | ### Functions
32 | ###############
33 | sub _create_session {
34 | my ($server, $comm) = @_;
35 | my $version = 1;
36 | my ($sess, $err) = Net::SNMP->session( -hostname => $server, -version => $version, -community => $comm);
37 | if (!defined($sess)) {
38 | print "Can't create SNMP session to $server\n";
39 | exit(1);
40 | }
41 | return $sess;
42 | }
43 |
44 | sub _get_oid_value(@) {
45 | my $sess = shift;
46 | my $local_oid = shift;
47 | my $r_return = $sess->get_request(-varbindlist => [$local_oid]);
48 | return($r_return->{$local_oid});
49 | }
50 |
51 | sub FSyntaxError($) {
52 | my $err = shift;
53 | print < internal,external
59 | -c = Critical Value -> internal,external
60 | EOU
61 | exit(1);
62 | }
63 |
64 | my %opt;
65 | my $result = GetOptions(\%opt,
66 | 'host|H=s',
67 | 'com|C=s',
68 | 'warn|w=s',
69 | 'crit|c=s',
70 | );
71 |
72 | FSyntaxError("Missing -H") unless defined $opt{'host'};
73 | FSyntaxError("Missing -C") unless defined $opt{'com'};
74 | FSyntaxError("Missing -w") unless defined $opt{'warn'};
75 | FSyntaxError("Missing -c") unless defined $opt{'crit'};
76 |
77 |
78 | # Validate Warning
79 | my @warn = split(",",$opt{'warn'});
80 | my @crit = split(",",$opt{'crit'});
81 | if($warn[0] > $crit[0]) {
82 | FSyntaxError("Warning can't be larger then Critical: $warn[0] > $crit[0]");
83 | }
84 | if($warn[1] > $crit[1]) {
85 | FSyntaxError("Warning can't be larger then Critical: $warn[1] > $crit[1]");
86 | }
87 |
88 | # Establish SNMP Session
89 | our $snmp_session = _create_session($opt{'host'},$opt{'com'});
90 | my $internal = _get_oid_value($snmp_session,$s_internal);
91 | my $external = _get_oid_value($snmp_session,$s_external);
92 | $internal = $internal / 100.0;
93 | $external = $external / 100.0;
94 |
95 | my $istat = 0;
96 | my $estat = 0;
97 |
98 | # Check Internal
99 | if($internal >= $crit[0]) {
100 | $istat=2;
101 | } elsif($internal >= $warn[0] and $internal < $crit[0]) {
102 | $istat=1;
103 | } else {
104 | $istat=0;
105 | }
106 |
107 | # Check External
108 | if($external >= $crit[1]) {
109 | $estat=2;
110 | } elsif($external >= $warn[1] and $external < $crit[1]) {
111 | $estat=1;
112 | } else {
113 | $estat=0;
114 | }
115 |
116 | if($istat == 2 or $estat == 2) {
117 | $stat = 2;
118 | $msg = "CRIT: $msg";
119 | } elsif($istat == 1 or $estat == 1) {
120 | $stat = 1;
121 | $msg = "WARN: $msg";
122 | } else {
123 | $stat = 0;
124 | $msg = "OK: $msg";
125 | }
126 |
127 | # Perf Data
128 | $perf="internal=$internal external=$external";
129 |
130 | print "$msg | $perf\n";
131 | exit($stat);
132 |
--------------------------------------------------------------------------------
/nagios/check_activemq.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | '''
4 | Monitor ActiveMQ server via its http web interface
5 | '''
6 |
7 | from HTMLParser import HTMLParser
8 | from optparse import OptionParser
9 | import xml.etree.ElementTree as ET
10 | import urllib2
11 | import urllib
12 |
13 | EXIT_CODE = {
14 | 'OK': 0,
15 | 'WARN': 1,
16 | 'CRIT': 2,
17 | 'UNKNOWN': 3,
18 | }
19 |
20 | def prepareOpts():
21 | '''
22 | Parse options from the shell
23 | '''
24 |
25 | cmds = {
26 | 'queues' : 'notify if there is a least one queue with no consumers (--exlcude)',
27 | 'consumer': 'notify if the specific consumers does not consume the queues (--queues, --client)',
28 | }
29 | def err( string ):
30 | print 'Error: {0}'.format( string )
31 | print __doc__
32 | parser.print_help()
33 | print '\nTypes:'
34 | for k in cmds:
35 | print ' {0}: {1}'.format(k ,cmds[k])
36 | exit(1)
37 |
38 | parser = OptionParser()
39 | parser.add_option('-H', '--server', dest='server', type='string', help='ActiveMQ fqdn or ip', default='localhost')
40 | parser.add_option('-U', '--user', dest='user', type='string', help='http username', default=None)
41 | parser.add_option('-P', '--password', dest='password', type='string', help='http password', default=None)
42 | parser.add_option('-p', '--port', dest='port', type='int', help='ActiveMQ web interface port', default=8161)
43 | parser.add_option('-t', '--timeout', dest='timeout', type='float', help='how many seconds to wait for each http request', default=5)
44 | parser.add_option('-T', '--type', dest='type', type='choice', choices=cmds.keys(), help='what to check: {0}'.format(cmds.keys()) )
45 | parser.add_option('-e', '--exclude', dest='exclude', type='string', help='csv list of queues to exclude (implies -T queues)', default=None )
46 | parser.add_option('-q', '--queues', dest='queues', type='string', help='csv list of queues (implies -T consumer)', default=None)
47 | parser.add_option('-c', '--client', dest='client', type='string', help='the client prefix to search (implies -T consumer)', default=None )
48 | (opts, args) = parser.parse_args()
49 |
50 | kargs = {}
51 |
52 | if opts.user is None and opts.password is not None:
53 | err('missing -P')
54 | elif opts.password is None and opts.user is not None:
55 | err('missing -U')
56 |
57 | if not opts.type:
58 | err('missing -T')
59 | elif opts.type == 'consumer':
60 | if opts.client is None:
61 | err('missing -c')
62 | if opts.queues is None:
63 | err('missing -q')
64 | else:
65 | kargs.update({'queues': opts.queues.split(',')})
66 | kargs.update({'client': opts.client})
67 | elif opts.exclude is not None:
68 | kargs.update({'exclude': opts.exclude.split(',')})
69 |
70 |
71 | return (opts, kargs)
72 |
73 | class AmqException(Exception):
74 | def __init__(self, msg, xcode):
75 | self.msg = msg
76 | self.xcode = xcode
77 | def __str__(self):
78 | return self.msg
79 | def getXcode(self):
80 | return self.xcode
81 | def getMsg(self):
82 | return self.msg
83 |
84 | class ConsumerHTMLParser(HTMLParser):
85 | '''
86 | Parse the consumers id from http://url/admin/queueConsumers.jsp?JMSDestination=QUEUENAME
87 | '''
88 |
89 | consumers = []
90 | table = False
91 | body = False
92 | tr = False
93 | td = False
94 | a = False
95 |
96 | def reset_vars(self):
97 | self.consumers = []
98 | self.table = False
99 | self.body = False
100 | self.tr = False
101 | self.td = False
102 | self.a = False
103 |
104 | def handle_starttag(self, tag, attrs):
105 | if self.td and tag == 'a':
106 | self.a = True
107 | elif self.tr and tag == 'td':
108 | self.td = True
109 | elif self.body and tag == 'tr':
110 | self.tr = True
111 | elif self.table and tag == 'tbody':
112 | self.body = True
113 | elif tag == 'table':
114 | self.table = ('id', 'messages') in attrs
115 |
116 | def handle_data(self, data):
117 | if self.a:
118 | if not data in self.consumers:
119 | self.consumers.append( data )
120 | self.a = False
121 | self.td = False
122 | self.tr = False
123 |
124 | def get_consumers(self):
125 | return self.consumers
126 |
127 | class ActivemqMonitor():
128 | '''
129 | Monitor ActiveMQ via http web interface
130 | '''
131 |
132 | def __init__(self, server, port, timeout, user=None, password=None, realm='ActiveMQRealm'):
133 | self.url = 'http://{0}:{1}'.format(server, port)
134 | self.server = server
135 | self.port = port
136 | self.timeout = timeout
137 | self.user = user
138 | self.password = password
139 | self.realm = realm
140 | if user is not None and password is not None:
141 | urllib2.install_opener(
142 | self._auth(
143 | self.url, self.user, self.password, self.realm
144 | )
145 | )
146 |
147 | def _auth(self, uri, user, password, realm):
148 | '''
149 | returns a authentication handler.
150 | '''
151 |
152 | basic = urllib2.HTTPBasicAuthHandler()
153 | basic.add_password(
154 | realm=realm, uri=uri, user=user, passwd=password
155 | )
156 | digest = urllib2.HTTPDigestAuthHandler()
157 | digest.add_password(
158 | realm=realm, uri=uri, user=user, passwd=password
159 | )
160 |
161 | return urllib2.build_opener(basic, digest)
162 |
163 | def _wget(self, url):
164 | '''
165 | create the http request to AMQ web UI
166 | '''
167 |
168 | try:
169 | ret = urllib2.urlopen(url, timeout=self.timeout).read()
170 | except urllib2.URLError:
171 | raise AmqException(
172 | 'UNKNOWN: Could not create http request to ActiveMQ',
173 | EXIT_CODE['UNKNOWN']
174 | )
175 |
176 | return ret
177 |
178 | def _getQueueConsumers(self, queue, parser):
179 | '''
180 | Get the parsed data of the queue
181 | '''
182 |
183 | url = '{0}/admin/queueConsumers.jsp?{1}'.format(
184 | self.url,
185 | urllib.urlencode( { 'JMSDestination': queue } ),
186 | )
187 | parser.reset_vars()
188 | parser.feed( self._wget(url) )
189 | return parser.get_consumers()
190 |
191 | def _eval_queues(self, res, opts):
192 | if res:
193 | return {
194 | 'msg': 'CRIT: the following queues are not consumed {0}'.format(','.join(res)),
195 | 'exit': EXIT_CODE['CRIT']
196 | }
197 | else:
198 | return {
199 | 'msg': 'OK: All the queues are consumed',
200 | 'exit': EXIT_CODE['OK']
201 | }
202 |
203 | def _eval_consumer(self, res, opts):
204 | if res:
205 | return {
206 | 'msg': 'CRIT: the following queues are not consumed by {0} {1}'.format(
207 | opts.client, ','.join(res)
208 | ),
209 | 'exit': EXIT_CODE['CRIT']
210 | }
211 | else:
212 | return {
213 | 'msg': 'OK: {0} is consuming all of its queues'.format(opts.client),
214 | 'exit': EXIT_CODE['OK']
215 | }
216 |
217 | def queues(self, exclude=[]):
218 | '''
219 | return all the queues with zero consumers
220 | '''
221 | errors = []
222 | url = '{0}/admin/xml/queues.jsp'.format(self.url, )
223 | html = self._wget(url)
224 | for q in ET.fromstring( html ).findall('queue'):
225 | if q.get('name') not in exclude and int(q.find('stats').get('consumerCount')) <= 0:
226 | errors.append(q.get('name'))
227 |
228 | return errors
229 |
230 | def consumer(self, client, queues):
231 | '''
232 | check if the clientid is configured as a subscriber on the queue
233 | '''
234 |
235 | missing = list(queues)
236 | parser = ConsumerHTMLParser()
237 | for queue in queues:
238 | for consumer in self._getQueueConsumers(queue, parser):
239 | if client in consumer:
240 | missing.remove(queue)
241 | break
242 |
243 | return missing
244 |
245 | @staticmethod
246 | def main():
247 | '''
248 | Main function
249 | '''
250 | (opts, kargs) = prepareOpts()
251 | amq = ActivemqMonitor(
252 | opts.server, opts.port, opts.timeout, opts.user, opts.password
253 | )
254 |
255 | method = getattr(amq, opts.type)
256 | try:
257 | res = method(**kargs)
258 | except AmqException as e:
259 | print e.getMsg()
260 | exit(e.getXcode())
261 |
262 | eval_method = getattr(
263 | amq, '_eval_{0}'.format(opts.type)
264 | )
265 | ret = eval_method(res, opts)
266 | print ret['msg']
267 | exit(ret['exit'])
268 |
269 | if __name__ == '__main__':
270 | ActivemqMonitor.main()
271 |
--------------------------------------------------------------------------------
/nagios/check_deep_fs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | """
4 | Monitor a mount on the filesystem and all of it sub mounts
5 | """
6 |
7 | from optparse import OptionParser
8 | import subprocess
9 | import os.path
10 |
11 |
12 | def parse_args():
13 | parser = OptionParser()
14 | parser.add_option('-p', '--path', dest='path', type='string', help='absolute path to check', metavar="FILE")
15 | parser.add_option('-w', '--warning', dest='warning', type='int', help='free disk space critical threshold (in %)')
16 | parser.add_option('-c', '--critical', dest='critical', type='int', help='free disk space warning threshold (in %)')
17 | (opts, args) = parser.parse_args()
18 |
19 | if opts.path is None:
20 | print 'UNKNOWN: -p'
21 | parser.print_help()
22 | exit(3)
23 | if opts.warning is None or opts.critical is None:
24 | print 'UNKNOWN: missing -w and/or -c'
25 | parser.print_help()
26 | exit(3)
27 | if opts.warning < opts.critical:
28 | print 'UNKNOWN: -c can not be greater than -w'
29 | parser.print_help()
30 | exit(3)
31 | if opts.path.endswith('/') and opts.path != '/':
32 | opts.path = opts.path[:-1]
33 | if not os.path.exists(opts.path):
34 | print 'UNKNOWN: -p "{0}" must be a valid path'.format(opts.path)
35 | parser.print_help()
36 | exit(3)
37 |
38 | return opts
39 |
40 |
41 | def get_mount_point(loc):
42 | '''
43 | Get the mount point of the path
44 | '''
45 |
46 | mount = os.path.realpath(os.path.abspath(loc))
47 | while not os.path.ismount(mount):
48 | mount = os.path.dirname(mount)
49 |
50 | return mount
51 |
52 |
53 | def get_df(mount):
54 | '''
55 | return a dict of {mount : free space in %}
56 | - sub mounts of `mount`
57 | - if mount is not a mount point return it's parent mount point as well
58 | '''
59 |
60 | res = {}
61 | real_path = get_mount_point(mount)
62 |
63 | proc = subprocess.Popen(
64 | 'df -P',
65 | shell=True,
66 | stdout=subprocess.PIPE,
67 | stderr=subprocess.PIPE,
68 | stdin=None
69 | )
70 | df = proc.communicate()[0].splitlines()
71 | df.pop(0)
72 |
73 | for line in df:
74 | data = line.split()
75 | path = data[-1]
76 | if mount in path or path == real_path:
77 | res.update({
78 | path: 100-int(data[-2].replace('%', ''))
79 | })
80 |
81 | return res
82 |
83 |
84 | xcode = 0
85 | opts = parse_args()
86 | df = get_df(opts.path)
87 | errors = []
88 |
89 | for mount, disk_free in df.items():
90 | if opts.warning >= disk_free > opts.critical:
91 | if xcode < 1:
92 | xcode = 1
93 | errors.append(mount)
94 | elif disk_free < opts.critical:
95 | if xcode < 2:
96 | xcode = 2
97 | errors.append(mount)
98 |
99 | if xcode == 0:
100 | msg = 'OK: All mounts are ok'
101 | else:
102 | if xcode == 1:
103 | err = 'WARN'
104 | else:
105 | err = 'CRIT'
106 | msg = '{0}: the mount {1} does not have enough disk space'.format(
107 | err, ','.join(errors)
108 | )
109 |
110 | print msg
111 | exit(xcode)
112 |
--------------------------------------------------------------------------------
/nagios/check_flexlm.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | # Info
15 | # This script is mainly for performance graph using pnp the usage of the license
16 |
17 | use strict;
18 |
19 | sub FSyntaxError {
20 | print "Syntax Error !\n";
21 | print "$0 [absolute path to lmutil] [absolute path to license file] [feature full name (from lmstat)]\n";
22 | exit(1);
23 | }
24 |
25 | if($#ARGV != 3) {
26 | FSyntaxError;
27 | }
28 |
29 | # General Settings
30 | my $lmutil = "$ARGV[0]"; chomp($lmutil);
31 | my $lm_file = "$ARGV[1]"; chomp($lm_file);
32 | my $feature = "$ARGV[2]"; chomp($feature);
33 | my $daemon = "$ARGV[3]";
34 | my $vendor = `basename $lm_file | sed 's/.lic//g'`; chomp($vendor);
35 |
36 | my @lmstat_out = split(";",`$lmutil lmstat -c $lm_file -S $daemon | grep ^Users\\ of\\ $feature: | sed -e 's/:/;/g' -e 's/ (Total of //g' -e 's/ Total of //g' -e 's/ licenses issued//g' -e 's/ licenses in use)\$//g' -e 's/ license issued//g' -e 's/ license in use)\$//g' -e 's/^Users of //g'`);
37 | if($#lmstat_out < 1) {
38 | print "$vendor $daemon Is Down\n";
39 | exit(2);
40 | }
41 |
42 | print "$vendor $daemon $feature | total=$lmstat_out[1] used=$lmstat_out[2]\n";
43 | exit(0);
44 |
--------------------------------------------------------------------------------
/nagios/check_flexlm_up.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | # Settings
15 |
16 | lmutil="/path/to/lmutil"
17 |
18 | function FError() {
19 | echo "Syntax:"
20 | echo "$0 [licesnse server dns name] [port #]"
21 | exit 3
22 | }
23 |
24 | if [ $# != 2 ]
25 | then
26 | FError
27 | fi
28 |
29 | server=$1
30 | port=$2
31 |
32 | $lmutil lmstat -c ${port}@${server} &> /dev/null
33 | ERR=$?
34 | if [ $ERR == 0 ]
35 | then
36 | echo "Flexlm: OK - ${port}@${server}| flexlm=1"
37 | exit 0
38 | else
39 | echo "Flexlm: Crit - ${port}@${server} | flexlm=0"
40 | exit 2
41 | fi
42 |
--------------------------------------------------------------------------------
/nagios/check_internet.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | # Checking User Input
15 | function FError()
16 | {
17 | echo "Syntax:"
18 | echo "$0 [url] [number of tries] [time out]"
19 | echo "Example:"
20 | echo "$0 www.google.com 2 5"
21 | exit 1
22 | }
23 |
24 | if [ $# != 3 ]
25 | then
26 | FError
27 | fi
28 |
29 | url="$1"
30 |
31 | if [ `echo $2 | grep -q ^[[:digit:]]*$ ; echo $?` == 0 ]
32 | then
33 | tries="$2"
34 | else
35 | FError
36 | fi
37 |
38 | if [ `echo $3 | grep -q ^[[:digit:]]*$ ; echo $?` == 0 ]
39 | then
40 | timeout="$3"
41 | else
42 | FError
43 | fi
44 |
45 | wget=`which wget`
46 |
47 |
48 | wget_code=`$wget $url -q -O /dev/null -t $tries --timeout $timeout ; echo $?`
49 |
50 | if [ $wget_code == 0 ]
51 | then
52 | echo "Internet Access Ok - $url | internet=1;0;0"
53 | exit 0
54 | else
55 | echo "Internet Access Failed - $url | internet=0;0;0"
56 | exit 2
57 | fi
58 |
59 |
--------------------------------------------------------------------------------
/nagios/check_modjk.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | '''
4 | Nagios compatible plugin to check Apache Modjk
5 |
6 | requires
7 | - Python >= 2.6
8 | - status worker enable
9 | '''
10 |
11 | from optparse import OptionParser
12 | import urllib2
13 | import re
14 |
15 | EXIT_CODE = {
16 | 'OK': 0,
17 | 'WARN': 1,
18 | 'CRIT': 2,
19 | 'UNKNOWN': 3,
20 | }
21 |
22 |
23 | def prepare_opts():
24 | '''
25 | Parse option from the shell
26 | '''
27 |
28 | def help():
29 | print 'How many workers are in OK state and Activated'
30 | print ''
31 | parser.print_help()
32 |
33 | def err( string ):
34 | print 'Error: {0}'.format( string )
35 | help()
36 | exit(1)
37 |
38 | parser = OptionParser()
39 | parser.add_option('-u', '--url', dest='url', type='string', help='modjk status worker url')
40 | parser.add_option('-c', '--critical', dest='critical', type='int', help='warning threshold', default=-1)
41 | parser.add_option('-w', '--warning', dest='warning', type='int', help='critical threshold', default=-1)
42 | parser.add_option('-t', '--timeout', dest='timeout', type='float', help='how many seconds to wait for each http request', default=5)
43 | (opts, args) = parser.parse_args()
44 |
45 | # Input Validation
46 | if not opts.url:
47 | err('missing Modjk Status http url')
48 | if opts.warning < opts.critical:
49 | err('-w can not be smaller than -c')
50 | if opts.warning < 0 or opts.critical < 0:
51 | err('-w and -c must be a positive number')
52 |
53 | return opts
54 |
55 |
56 | def get_error_workers(url, timeout):
57 | '''
58 | Query the Modjk status worker for bad workers
59 | '''
60 |
61 | get_node = re.compile(r'Member: name=(.*) type=')
62 | ret = set([])
63 | total = 0
64 | response = urllib2.urlopen(url+'?mime=txt', timeout=timeout).read()
65 | for member in re.findall( r'^Member: .*', response, re.M):
66 | total += 1
67 | if 'state=OK' in member and 'activation=ACT' in member:
68 | ret.add(
69 | get_node.search(member).groups(0)[0]
70 | )
71 | return (list(ret), total)
72 |
73 |
74 | if __name__ == '__main__':
75 | opts = prepare_opts()
76 |
77 | try:
78 | (errorWorkers, total) = get_error_workers(
79 | opts.url, opts.timeout
80 | )
81 | except urllib2.URLError as e:
82 | print 'UNKNOWN: Cant query jkstatus worker for data'
83 | exit(EXIT_CODE['UNKNOWN'])
84 |
85 | count = len(errorWorkers)
86 | state = ''
87 | if count > opts.warning or (opts.warning == 1 and count == 1):
88 | state = 'OK'
89 | elif opts.warning >= count > opts.critical:
90 | state = 'WARN'
91 | else:
92 | state = 'CRIT'
93 |
94 | print '{0}: {1}/{2} workers are OK and ACT {3}'.format(
95 | state, count, total, ','.join(errorWorkers)
96 | )
97 | exit(EXIT_CODE[state])
98 |
--------------------------------------------------------------------------------
/nagios/check_sgeexec.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | use strict;
15 | use XML::Simple;
16 |
17 | sub FSyntaxError {
18 | print "Syntax Error !\n";
19 | print "$0 [s|q] [absolute path to settings.sh] [hostname] [queue name]\n";
20 | print "s = Status of the exec hosts: check for Error status, and if he has a queue instance enabled\n";
21 | print "q = check via qrsh is the host accepts jobs (you can configure a queue for all the exec hosts with access list only to nagios for the sake of this check)\n\n";
22 | print "Example:\n";
23 | print "$0 q /path/to/settings.sh quad-8g1 nagios.q\n";
24 | print "$0 s /path/to/settings.sh quad-8g1 [queues,to,exclude]\n";
25 | exit(1);
26 | }
27 |
28 | # User Input
29 | if($#ARGV < 2) {
30 | FSyntaxError;
31 | }
32 | my $check_type = shift(@ARGV);
33 | my $sge_settings = shift(@ARGV);
34 | my $sgeexecd = shift(@ARGV);
35 |
36 |
37 | # General Settings
38 | my $exit = 0;
39 | my $perf;
40 | my $msg;
41 |
42 | if("$check_type" eq "q") {
43 | # Check via qrsh
44 | my $queue = shift(@ARGV);
45 | my $qrsh = `source $sge_settings ; qrsh -q $queue\@$sgeexecd hostname &> /dev/null ; echo \$?`;
46 | chomp($qrsh);
47 | if($qrsh != 0) {
48 | $exit = 2;
49 | $perf = "qrsh=0";
50 | $msg = "$queue\@$sgeexecd cant execute jobs";
51 | } else {
52 | $perf = "qrsh=1";
53 | $msg = "$queue\@$sgeexecd can execute jobs";
54 | }
55 | } elsif("$check_type" eq "s") {
56 | # Check Host's queue instance Status
57 | my $queue_list_2_exclude = shift(@ARGV);
58 | my @queues2ex = split(',',$queue_list_2_exclude);
59 | my $queue_instances = 0;
60 | my $queue_instances_err = 0;
61 | $perf = "qstatus=1";
62 | my @qstat_out = split("\n",`source $sge_settings ; qhost -q -h $sgeexecd`); shift(@qstat_out);shift(@qstat_out);shift(@qstat_out);shift(@qstat_out);
63 |
64 | foreach my $line (@qstat_out) {
65 | my @cline = split(" ",$line);
66 | my $yes_exclude = 0;
67 | foreach my $q (@queues2ex) {
68 | if($q eq $cline[0]) {
69 | $yes_exclude++;
70 | last;
71 | }
72 | }
73 |
74 | if($yes_exclude == 0) {
75 | if($cline[3] =~ /E/) {
76 | $msg = "$msg $cline[0]\@$sgeexecd in Error status.";
77 | $queue_instances_err++;
78 | }
79 | unless($cline[3] =~ /d/) {
80 | $queue_instances++;
81 | }
82 | }
83 | }
84 |
85 | if($queue_instances == 0 or $queue_instances_err > 0) {
86 | if($queue_instances_err > 0) {
87 | $perf = "qstatus=$queue_instances_err";
88 | } else {
89 | $perf = "qstatus=0";
90 | }
91 | if($queue_instances == 0) {
92 | $perf = "$perf qconfigured=0";
93 | $msg = "$msg $sgeexecd dont have any queue configured.";
94 | } else {
95 | $perf = "$perf qconfigured=$queue_instances";
96 | }
97 | $exit = 2;
98 | } else {
99 | $exit = 0;
100 | $msg = "$sgeexecd is OK";
101 | $perf = "qstatus=0 qconfigured=$queue_instances";
102 | }
103 | } else {
104 | FSyntaxError;
105 | }
106 |
107 |
108 | # Display Message
109 | if($exit == 0) {
110 | $msg = "OK: $msg";
111 | } else {
112 | $msg = "Error: $msg";
113 | }
114 | print "$msg | $perf\n";
115 | exit($exit);
116 |
117 |
--------------------------------------------------------------------------------
/nagios/check_solr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | '''
4 | Nagios compatible plugin to check Solr via Solr HTTP API
5 |
6 | require Python >= 2.6
7 | '''
8 |
9 | from optparse import OptionParser
10 | import xml.etree.ElementTree as ET
11 | import urllib2
12 | import tempfile
13 | import os.path
14 |
15 | EXIT_CODE = {
16 | 'OK': 0,
17 | 'WARN': 1,
18 | 'CRIT': 2,
19 | 'UNKNOWN': 3,
20 | }
21 |
22 | def prepareOpts():
23 | '''
24 | Parse option from the shell
25 | '''
26 |
27 | cmds = {
28 | 'ping' : 'create a ping to solr API',
29 | 'dataimportDocumentsProcessed': 'check that the dataimport handler is not processing the same document for too long',
30 | 'indexBehindMaster': 'check the difference between the slave index and the master'
31 | }
32 | epliog = 'Type of Checks:'
33 | for k in cmds:
34 | epliog += '\n {0}:\t{1}'.format(k, cmds[k])
35 |
36 | def help():
37 | parser.print_help()
38 | print ''
39 | print epliog
40 |
41 | def err( string ):
42 | print 'Error: {0}'.format( string )
43 | help()
44 | exit(1)
45 |
46 | parser = OptionParser()
47 | parser.add_option('-u', '--url', dest='url', type='string', help='solr url', default=None)
48 | parser.add_option('-U', '--user', dest='user', type='string', help='username', default=None)
49 | parser.add_option('-P', '--passwd', dest='passwd', type='string', help='password', default=None)
50 | parser.add_option('-t', '--timeout', dest='timeout', type='float', help='how many seconds to wait for each http request', default=5)
51 | parser.add_option('-T', '--type', dest='type', type='choice', choices=cmds.keys(), help='what to check: {0}'.format(', '.join(cmds.keys())) )
52 | parser.add_option('-C', '--core', dest='core', type='string', help='core id', default=None)
53 | parser.add_option('-d', '--handler', dest='handler', type='string', help='dataimport handler name', default=None)
54 | parser.add_option('-c', '--critical', dest='critical', type='int', help='warning threshold (implies -T indexBehindMaster)', default=None)
55 | parser.add_option('-w', '--warning', dest='warning', type='int', help='critical threshold (implies -T indexBehindMaster)', default=None)
56 | parser.add_option('-m', '--tmpdir', dest='tmpdir', type='string', help='absolute path to a writeable directory on the server', default=tempfile.gettempdir())
57 | (opts, args) = parser.parse_args()
58 |
59 | # Input Validation
60 | if not opts:
61 | help()
62 | exit(1)
63 | if not opts.type:
64 | err('missing -T')
65 | if (opts.user and not opts.passwd) or (not opts.user and opts.passwd):
66 | err('missing username or password')
67 | if not opts.url:
68 | err('missing solr http url')
69 | if opts.type == 'dataimportDocumentsProcessed':
70 | if opts.core is None:
71 | err('missing core id !')
72 | if opts.handler is None:
73 | err('missing handler name !')
74 | if opts.type == 'indexBehindMaster':
75 | if opts.critical is None or opts.warning is None:
76 | err('missing -w or -c')
77 | if opts.warning > opts.critical:
78 | err('-w can not be greater than -c')
79 |
80 | return opts
81 |
82 |
83 | class SolrMonitor():
84 | '''
85 | Monitor Apache Solr via http
86 | '''
87 |
88 | def __init__(self, url, timeout=5, username=None, passwd=None):
89 | self.url = url
90 | self.timeout = timeout
91 | self.username = username
92 | self.passwd = passwd
93 | self.memfile = 'check_solr_data'
94 |
95 | if self.url.endswith('/'):
96 | self.url = self.url[:-1]
97 |
98 | self._get_auth()
99 |
100 | def _get_auth(self):
101 | '''
102 | Build an Auth opener for HTTP connection
103 | '''
104 | if not self.username or not self.passwd:
105 | return
106 | basic = urllib2.HTTPBasicAuthHandler()
107 | basic.add_password(
108 | realm='Solr',
109 | uri=self.url,
110 | user=self.username,
111 | passwd=self.passwd
112 | )
113 | digest = urllib2.HTTPDigestAuthHandler()
114 | digest.add_password(
115 | realm='Solr',
116 | uri=self.url,
117 | user=self.username,
118 | passwd=self.passwd
119 | )
120 |
121 | urllib2.install_opener(
122 | urllib2.build_opener(basic, digest))
123 |
124 | def _getXmlData(self, url):
125 | '''
126 | create an http request to url and return the data
127 | in case of a problem return None
128 | '''
129 |
130 | try:
131 | return ET.fromstring(
132 | urllib2.urlopen(
133 | url,
134 | timeout=self.timeout
135 | ).read()
136 | )
137 | except urllib2.URLError:
138 | return None
139 |
140 | def _eval_ping(self, res, opts):
141 | '''
142 | Evaluate the ping test
143 | '''
144 |
145 | if res:
146 | return {
147 | 'exit': EXIT_CODE['OK'],
148 | 'msg': 'OK: Solr Ping is up'
149 | }
150 | else:
151 | return {
152 | 'exit': EXIT_CODE['CRIT'],
153 | 'msg': 'CRIT: Solr Ping is down'
154 | }
155 |
156 | def _eval_dataimportDocumentsProcessed(self, res, opts):
157 | '''
158 | Evaluate the dataimportDocumentsProcessed test
159 | '''
160 | firstTimeResponse = {
161 | 'exit': EXIT_CODE['UNKNOWN'],
162 | 'msg': 'UNKNOWN: looks like the first time we are using this check, creating local cache'
163 | }
164 | memFile = os.path.join(opts.tmpdir, self.memfile)
165 | if not os.path.isfile(memFile):
166 | with open( memFile, 'w' ) as f:
167 | f.write(str(res))
168 | return firstTimeResponse
169 |
170 | if res < 0:
171 | return {
172 | 'exit': EXIT_CODE['UNKNOWN'],
173 | 'msg': 'UNKNOWN: could not query solr for index status'
174 | }
175 |
176 | fh = open( memFile, 'r+' )
177 | prev = fh.read()
178 | fh.seek(0)
179 | fh.write(str(res))
180 | fh.close()
181 | if not prev:
182 | return firstTimeResponse
183 | prev = int(prev)
184 |
185 | if prev != res or res == 0:
186 | return {
187 | 'exit': EXIT_CODE['OK'],
188 | 'msg': 'OK: Solr is indexing {0} docs now and before {1}'.format(
189 | res, prev
190 | )
191 | }
192 | else:
193 | return {
194 | 'exit': EXIT_CODE['CRIT'],
195 | 'msg': 'CRIT: Solr is still indexing {0} docs since the last check'.format(res)
196 | }
197 |
198 | def _eval_indexBehindMaster(self, res, opts):
199 | '''
200 | Evaluate the indexBehindMaster test
201 | '''
202 |
203 | msg=''
204 | if res < opts.warning:
205 | msg='OK'
206 | elif res >= opts.warning and res <= opts.critical:
207 | msg='WARN'
208 | else:
209 | msg='CRIT'
210 | return {
211 | 'exit': EXIT_CODE[msg],
212 | 'msg': '{0}: Solr Slave is {1} behind then master'.format(
213 | msg, res
214 | )
215 | }
216 |
217 | def ping(self):
218 | '''
219 | Check if solr ping returns True
220 | '''
221 |
222 | ret = False
223 | root = self._getXmlData(self.url + '/admin/ping')
224 | if root is None:
225 | return False
226 |
227 | if root.find('str').text == 'OK':
228 | ret = True
229 |
230 | return ret
231 |
232 | def dataimportDocumentsProcessed(self, core, handler):
233 | '''
234 | Return the number of processed documents
235 | from the dataimport handler
236 |
237 | url: http://solr:port/solr/core0/dataimportName?command=status
238 | '''
239 |
240 | url = '{0}/{1}/{2}?command=status'.format(
241 | self.url,
242 | core,
243 | handler
244 | )
245 | root = self._getXmlData(url)
246 | if root is None:
247 | return -1
248 |
249 | for lst in root.findall('lst'):
250 | if lst.attrib['name'] == 'statusMessages':
251 | for str in lst.findall('str'):
252 | if str.attrib['name'] == 'Total Documents Processed':
253 | return int(str.text)
254 |
255 | return -1
256 |
257 | # Python 2.7
258 | # return int(
259 | # root.findall(
260 | # "lst[@name='statusMessages']/str[@name='Total Documents Processed']"
261 | # )[0].text
262 | # )
263 |
264 | def indexBehindMaster(self):
265 | '''
266 | Returns the difference bewteen the slave index
267 | and the master replicable index
268 | '''
269 |
270 | slave = None
271 | master = None
272 | root = self._getXmlData(
273 | self.url + '/replication?command=details'
274 | )
275 | if root is None:
276 | return -1
277 |
278 | for lst in root.findall('lst'):
279 | if lst.attrib['name'] == 'details':
280 |
281 | # Slave
282 | for lng in lst.findall('long'):
283 | if lng.attrib['name'] == 'indexVersion':
284 | slave = long(lng.text)
285 | break
286 |
287 | # Master
288 | for lstm in lst.findall('lst'):
289 | if lstm.attrib['name'] == 'slave':
290 | for lstms in lstm.findall('lst'):
291 | if lstms.attrib['name'] == 'masterDetails':
292 | for lstMaster in lstms.findall('lst'):
293 | if lstMaster.attrib['name'] == 'master':
294 | for rep in lstMaster.findall('long'):
295 | if rep.attrib['name'] == 'replicableVersion':
296 | master = long(rep.text)
297 | break
298 |
299 | if master and slave:
300 | break
301 |
302 | # Python 2.7
303 | # slave = root.findall(
304 | # "./*[@name='details']/arr[@name='commits']/lst/long[@name='indexVersion']"
305 | # )[0].text
306 | # master = root.findall(
307 | # "./lst[@name='details']/lst[@name='slave']/lst[@name='masterDetails']/lst[@name='master']/long[@name='replicableVersion']"
308 | # )[0].text
309 | return long(master - slave)
310 |
311 | @staticmethod
312 | def main():
313 | '''
314 | Main function
315 | '''
316 |
317 | opts = prepareOpts()
318 | solr = SolrMonitor( opts.url, opts.timeout, opts.user, opts.passwd )
319 |
320 | method = getattr(solr, opts.type)
321 | k = {}
322 | if opts.core:
323 | k.update({'core': opts.core})
324 | if opts.handler:
325 | k.update({'handler': opts.handler})
326 | res = method(**k)
327 |
328 | eval_method = getattr(
329 | solr, '_eval_{0}'.format(opts.type)
330 | )
331 | ret = eval_method(res, opts)
332 | print ret['msg']
333 | exit(ret['exit'])
334 |
335 |
336 |
337 | if __name__ == '__main__':
338 | SolrMonitor.main()
339 |
--------------------------------------------------------------------------------
/nagios/check_svn.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | function FError()
15 | {
16 | echo "Syntax:"
17 | echo "$0 [svn server] [http | svn | https] [repos path] [location to check-out] [username] [password]"
18 | echo "for this check you'll need to create a repository name nagios"
19 | echo "Example:"
20 | echo "$0 svnsrv http,https CM ${RANDOM}"
21 | exit 1
22 | }
23 |
24 | function FCheckHttps()
25 | {
26 | mkdir -p $WORKINGCOPY
27 | cd $WORKINGCOPY
28 | svn co https://${SVNSRV}/${REPOPATH}/nagios --no-auth-cache --config-dir /home/nagios/.subversion --username $SVNUSER --password $SVNPASS $WORKINGCOPY &> /dev/null
29 | if [ $? != 0 ]
30 | then
31 | rm -rf $WORKINGCOPY
32 | ERR=`expr $ERR + 1`
33 | MSG="$MSG https: Error"
34 | PERF="$PERF https=0;0;0;;"
35 | else
36 | rm -rf $WORKINGCOPY
37 | ERR=`expr $ERR + 0`
38 | MSG="$MSG https: ok"
39 | PERF="$PERF https=1;0;0;;"
40 | fi
41 | }
42 |
43 | function FCheckHttp()
44 | {
45 | mkdir -p $WORKINGCOPY
46 | cd $WORKINGCOPY
47 | svn co http://${SVNSRV}/${REPOPATH}/nagios --no-auth-cache --config-dir /home/nagios/.subversion --username $SVNUSER --password $SVNPASS $WORKINGCOPY &> /dev/null
48 | if [ $? != 0 ]
49 | then
50 | rm -rf $WORKINGCOPY
51 | ERR=`expr $ERR + 1`
52 | MSG="$MSG http: Error"
53 | PERF="$PERF http=0;0;0;;"
54 | else
55 | rm -rf $WORKINGCOPY
56 | ERR=`expr $ERR + 0`
57 | MSG="$MSG http: ok"
58 | PERF="$PERF http=1;0;0;;"
59 | fi
60 | }
61 |
62 | function FCheckSvn()
63 | {
64 | mkdir -p $WORKINGCOPY
65 | cd $WORKINGCOPY
66 | svn co svn://${SVNSRV}/nagios --no-auth-cache --config-dir /home/nagios/.subversion --username $SVNUSER --password $SVNPASS $WORKINGCOPY &> /dev/null
67 | if [ $? != 0 ]
68 | then
69 | rm -rf $WORKINGCOPY
70 | ERR=`expr $ERR + 1`
71 | MSG="$MSG svn: Error"
72 | PERF="$PERF svn=0;0;0;;"
73 | else
74 | rm -rf $WORKINGCOPY
75 | ERR=`expr $ERR + 0`
76 | MSG="$MSG svn: ok"
77 | PERF="$PERF svn=1;0;0;;"
78 | fi
79 | }
80 |
81 | if [ $# != 4 ]
82 | then
83 | FError
84 | fi
85 |
86 | SVNSRV="$1"
87 | PROTOCOL=`echo $2 | sed 's/,/ /g'`
88 | REPOPATH="$3"
89 | WORKINGCOPY="$4"
90 | SVNPORT="3690"
91 | HTTPPORT="80"
92 | HTTPSPORT="443"
93 | SVNUSER="$5"
94 | SVNPASS="$6"
95 | MSG=""
96 | PREF=""
97 | ERR="0"
98 |
99 | for proto in $PROTOCOL
100 | do
101 | case $proto in
102 | "https" )
103 | FCheckHttps
104 | ;;
105 | "http" )
106 | FCheckHttp
107 | ;;
108 | "svn" )
109 | FCheckSvn
110 | ;;
111 | * )
112 | FError
113 | ;;
114 | esac
115 | done
116 |
117 |
118 |
119 | if [ $ERR = 0 ]
120 | then
121 | echo "$MSG = OK | $PERF"
122 | exit 0
123 | else
124 | echo "$MSG = CRITICAL | $PERF"
125 | exit 2
126 | fi
127 |
128 | echo "Looking OK | Server:$SVNSRV Protocols:$PROTOCOL"
129 |
130 |
--------------------------------------------------------------------------------
/nagios/check_w32_mem.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | use strict;
15 | use Net::SNMP;
16 | my $stat;
17 | my $msg;
18 | my $perf;
19 |
20 | ### SNMP OIDs
21 | ###############
22 | my $S_Mem_Total = ".1.3.6.1.2.1.25.2.2.0"; # Byte
23 | my $S_Process_Mem_Util = ".1.3.6.1.2.1.25.5.1.1.2";
24 |
25 | ### Functions
26 | ###############
27 |
28 | sub _create_session {
29 | my ($server, $comm) = @_;
30 | my $version = 1;
31 | my ($sess, $err) = Net::SNMP->session( -hostname => $server, -version => $version, -community => $comm);
32 | if (!defined($sess)) {
33 | print "Can't create SNMP session to $server\n";
34 | exit(1);
35 | }
36 | return $sess;
37 | }
38 |
39 | sub FSyntaxError {
40 | print "Syntax Error !\n";
41 | print "$0 -H [ip|dnsname] -C [snmp community] -w [warning value] -c [critical value]\n";
42 | print "To disable warning and critical values type 200 as the value";
43 | exit(3);
44 | }
45 |
46 | if($#ARGV != 7) {
47 | FSyntaxError;
48 | }
49 |
50 | ### Gather input from user
51 | #############################
52 | my $switch;
53 | my $community;
54 | my $check_type;
55 | my $warn;
56 | my $crit;
57 |
58 | while(@ARGV) {
59 | my $temp = shift(@ARGV);
60 | if("$temp" eq '-H') {
61 | $switch = shift(@ARGV);
62 | } elsif("$temp" eq '-C') {
63 | $community = shift(@ARGV);
64 | } elsif("$temp" eq '-w') {
65 | $warn = shift(@ARGV);
66 | } elsif("$temp" eq '-c') {
67 | $crit = shift(@ARGV);
68 | } else {
69 | FSyntaxError();
70 | }
71 | }
72 |
73 | if($warn > $crit) {
74 | print "Warning can't be larger then Critical: $warn > $crit\n";
75 | FSyntaxError();
76 | }
77 |
78 | # Establish SNMP Session
79 | our $snmp_session = _create_session($switch,$community);
80 |
81 | # Total Memory
82 | my $R_Mem_Total = $snmp_session->get_request(-varbindlist => [$S_Mem_Total]);
83 | my $Mem_Total = "$R_Mem_Total->{$S_Mem_Total}";
84 |
85 | # Used Memory
86 | my $R_proc_tbl = $snmp_session->get_table($S_Process_Mem_Util);
87 | my $Mem_Used = 0;
88 | foreach my $oid ( keys %$R_proc_tbl) {
89 | # print "$oid\t$$R_proc_tbl{$oid}\n";
90 | $Mem_Used = $Mem_Used + $$R_proc_tbl{$oid};
91 | }
92 |
93 | # Free Memory
94 | my $Mem_Free = $Mem_Total - $Mem_Used;
95 | my $Mem_Free_P = int($Mem_Free / $Mem_Total * 100);
96 |
97 | # Humen Readable
98 | my $Mem_Total_H = int($Mem_Total / 1024);
99 | my $Mem_Used_H = int($Mem_Used / 1024);
100 | my $Mem_Free_H = int($Mem_Free / 1024);
101 |
102 | # Calculate Exit Status
103 | if($Mem_Free_P < $warn) {
104 | $stat = 0;
105 | $msg = "Memory: OK - Free Memory $Mem_Free_P%";
106 | } elsif($Mem_Free_P > $warn and $Mem_Free_P < $crit) {
107 | $stat = 1;
108 | $msg = "Memory: Warn - Free Memory $Mem_Free_P%";
109 | } elsif($Mem_Free_P > $crit) {
110 | $stat = 2;
111 | $msg = "Memory: CRIT - Free Memory $Mem_Free_P%";
112 | }
113 |
114 | $perf = "total=$Mem_Total_H used=$Mem_Used_H";
115 |
116 | print "$msg | $perf\n";
117 | exit($stat);
118 |
--------------------------------------------------------------------------------
/nagios/perf-linux-cpu.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 | #####################################
3 | #####################################
4 | ### ______ _ =) ###
5 | ### | ___ \ | | ###
6 | ### | |_/ / __ _ _ __ | | ###
7 | ### | / / _` || '_ \ | | ###
8 | ### | |\ \| (_| || | | || |____ ###
9 | ### \_| \_|\__,_||_| |_|\_____/ ###
10 | #####################################
11 | #####################################
12 |
13 | # Info
14 | #
15 | # Used only for performance monitoring via check_by_ssh
16 |
17 | my $msg = "MPSTAT Performance |";
18 | my $x = 0;
19 | my %header;
20 | my $fcount = -1;
21 | my $mpstat = `which mpstat`; chomp($mpstat);
22 | my @out = split("\n",`$mpstat |tail -n 2`);
23 | foreach my $line (@out) {
24 | my @chopped = split(" ",$line);
25 | shift(@chopped);shift(@chopped);shift(@chopped);
26 |
27 | my $count = 0;
28 | if($x == 0) {
29 | foreach my $field (@chopped) {
30 | if($field =~ /^%/) {
31 | $field =~ s/^%//; chomp($field);
32 | $fcount++;
33 | $header{"$fcount"} = $field;
34 | $count++;
35 | }
36 | }
37 | } else {
38 | for(my $i=0;$i<=$fcount;$i++) {
39 | my $tmp = int($chopped[$i]); chomp($tmp);
40 | $msg = "$msg $header{$i}=$tmp;0;0;0";
41 | }
42 | }
43 | $x++;
44 | }
45 |
46 | print "$msg\n";
47 | exit(0);
--------------------------------------------------------------------------------
/nagios/perf-sge.pl:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env perl
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | use strict;
15 | use Time::Local;
16 |
17 | # Used only for performance via pnp4Nagios
18 |
19 | sub FSyntaxError {
20 | print "Syntax Error !\n";
21 | print "$0 cjs \n";
22 | print "\tcjs = Cell Job Summary\n";
23 | print "$0 qjs \"queue name\"\n";
24 | print "\tqjs = Queue Job Summary\n";
25 | exit(3);
26 | }
27 |
28 | if($#ARGV < 0) {
29 | FSyntaxError;
30 | }
31 |
32 | my $sge_settings = "/path/to/sge/settings.sh";
33 | my $perf_data;
34 | my $msg;
35 | my $queue;
36 |
37 | sub cjs {
38 | my @qstat_grid_jobs = split("\n",`source $sge_settings ; qstat | sed '1,2d' | awk '{print \$5}' | sort`);
39 | my %sum_grid_jobs;
40 | $sum_grid_jobs{'r'} = 0;
41 | $sum_grid_jobs{'Eqw'} = 0;
42 | $sum_grid_jobs{'qw'} = 0;
43 | $sum_grid_jobs{'t'} = 0;
44 | $sum_grid_jobs{'other'} = 0;
45 | my $grid_job_sum = 0;
46 | $msg = "Cell Job Summary";
47 |
48 | foreach my $state (@qstat_grid_jobs) {
49 | chomp($state);
50 | $grid_job_sum++;
51 | if($state eq "r") {
52 | $sum_grid_jobs{'r'}++;
53 | } elsif($state eq "Eqw") {
54 | $sum_grid_jobs{'Eqw'}++;
55 | } elsif($state eq "qw") {
56 | $sum_grid_jobs{'qw'}++;
57 | } elsif($state eq "t") {
58 | $sum_grid_jobs{'t'}++;
59 | } else {
60 | $sum_grid_jobs{'other'}++;
61 | }
62 | }
63 |
64 | $perf_data = "Sum=$grid_job_sum;0;0 r=$sum_grid_jobs{'r'};0;0 qw=$sum_grid_jobs{'qw'};0;0 Eqw=$sum_grid_jobs{'Eqw'};0;0 t=$sum_grid_jobs{'t'};0;0 others=$sum_grid_jobs{'other'};0;0";
65 | }
66 |
67 | sub qjs {
68 | my @months = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
69 | my @qstat_queue_info = split(" ",`source $sge_settings ; qstat -g c | sed '1,2d' | grep ^$queue\\ `);
70 | my @jobs_id = split("\n",`source $sge_settings ; qstat | sed '1,2d' | grep $queue\@ | awk '{print \$1" "\$6" "\$7}'`);
71 | my %diff;
72 | $diff{'count'} = 0;
73 | $diff{'sum'} = 0;
74 | $msg = "$queue monitor";
75 |
76 | foreach my $jobsid (@jobs_id) {
77 | $diff{'count'}++;
78 | chomp($jobsid);
79 | my @jobsid_arr = split(" ",$jobsid);
80 | my @submit_time_raw = split(" ",`source $sge_settings ; qstat -j $jobsid_arr[0] | grep ^submission_time: | awk '{print \$3" "\$4" "\$5" "\$6}'`);
81 | my $mon_submit;
82 | my $x = 1;
83 | foreach my $month (@months) {
84 | if($month eq $submit_time_raw[0]) {
85 | $mon_submit = "$x";
86 | }
87 | $x = $x + 1;
88 | }
89 |
90 | my @submit_time_raw2 = split(":",$submit_time_raw[2]);
91 | my @exec_time_raw2 = split(":",$jobsid_arr[2]);
92 | my @exec_date_raw2 = split("/",$jobsid_arr[1]);
93 |
94 | ###time=timelocal($sec, $min, $hours, $day, $mon, $year)
95 | my $submit_time=timelocal($submit_time_raw2[2], $submit_time_raw2[1], $submit_time_raw2[0], $submit_time_raw[1], $mon_submit, $submit_time_raw[3]);
96 | my $exec_time=timelocal($exec_time_raw2[2], $exec_time_raw2[1], $exec_time_raw2[0], $exec_date_raw2[1], $exec_date_raw2[0], $exec_date_raw2[2]);
97 | my $diff = $exec_time - $submit_time;
98 | $diff{'sum'} = $diff{'sum'} + $diff;
99 | }
100 | my $job_avg;
101 | if($diff{'sum'} == 0) {
102 | $job_avg = 0;
103 | } else {
104 | $job_avg = $diff{'sum'} / $diff{'count'};
105 | }
106 | my $avail = $qstat_queue_info[2] + $qstat_queue_info[4];
107 | $perf_data = "$perf_data $qstat_queue_info[0]_used=$qstat_queue_info[2];0;0 $qstat_queue_info[0]_total=$avail;0;0 job_waiting_avg=$job_avg\sec;0;0";
108 | }
109 |
110 |
111 |
112 |
113 | if("$ARGV[0]" eq "cjs") {
114 | cjs();
115 | } elsif("$ARGV[0]" eq "qjs") {
116 | if($#ARGV < 1) {
117 | FSyntaxError;
118 | }
119 | $queue = "$ARGV[1]";
120 | my $is_queue_exists = `source $sge_settings ; qstat -g c | sed '1,2d' | grep -q ^$queue\\ ; echo \$?`;
121 | chomp($is_queue_exists);
122 | if("0" ne "$is_queue_exists") {
123 | FSyntaxError;
124 | }
125 | qjs();
126 |
127 | } else {
128 | FSyntaxError;
129 | }
130 |
131 | print "$msg | $perf_data \n";
132 | exit(0);
133 |
--------------------------------------------------------------------------------
/nagios/perf_ghs-float.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #####################################
4 | #####################################
5 | ### ______ _ =) ###
6 | ### | ___ \ | | ###
7 | ### | |_/ / __ _ _ __ | | ###
8 | ### | / / _` || '_ \ | | ###
9 | ### | |\ \| (_| || | | || |____ ###
10 | ### \_| \_|\__,_||_| |_|\_____/ ###
11 | #####################################
12 | #####################################
13 |
14 | # Info
15 | #
16 | # Get usage data from a GHS license server via the web managment console
17 | # use mainly for performance monitoring
18 |
19 | function FError() {
20 | echo "Syntax Error !"
21 | echo "$0 [license server name] [port] [feature name] [/path/to/ghs/log/file]"
22 | echo "port = port of the license web port"
23 | exit 1
24 | }
25 |
26 | if [ $# != 4 ]
27 | then
28 | FError
29 | fi
30 |
31 | if [ `echo $2 | grep -q ^[[:digit:]]*$ ; echo $?` != 0 ]
32 | then
33 | FError
34 | fi
35 |
36 | if [ ! -f "$4" ]
37 | then
38 | FError
39 | fi
40 |
41 | server="$1"
42 | port="$2"
43 | feature="$3"
44 | log_file="$4"
45 |
46 | min=`date +%M | cut -c 2`
47 | log_date_search="`date +%d``date +%b``date +%y` `date +%H`:`date +%M | cut -c 1`"
48 | if [ $min -lt 5 ]
49 | then
50 | min_list="0 1 2 3 4"
51 | else
52 | min_list="5 6 7 8 9 10"
53 | fi
54 |
55 | random_file=/tmp/$RANDOM
56 | while_file=/tmp/$RANDOM
57 | denied_file=/tmp/$RANDOM
58 | export msg="$server:$port is up"
59 | export perf_data=""
60 |
61 | if [ ! -f $log_file ]
62 | then
63 | echo "$log_file doesn't exists !"
64 | exit 2
65 | fi
66 |
67 | wget http://$server:$port -q -O $random_file
68 | if [ $? != 0 ]
69 | then
70 | msg="$server:$port is down"
71 | echo "$msg"
72 | exit 2
73 | fi
74 |
75 | cat $random_file | grep -v ^\< | grep -v ^$ | grep -v ^\ | sed -n '1,4!p' | sed -e 's///g' -e 's/<\/TD>//g' | sed -n /^$feature\$/,+2p > $while_file
76 |
77 | feature_exists=`head -n 1 $while_file | grep -q ^$feature$ ; echo $?`
78 |
79 | if [ $feature_exists != 0 ]
80 | then
81 | FError
82 | fi
83 |
84 | export counter=0
85 | while read line
86 | do
87 | counter=`expr $counter + 1`
88 | case $counter in
89 | 2 )
90 | export total="$line"
91 | ;;
92 | 3 )
93 | export used="$line"
94 |
95 | # Missed Licensed request
96 | for m in $min_list
97 | do
98 | grep "^${log_date_search}${m}" $log_file | grep "license denied: no $feature licenses available"$ | awk '{print $3}' >> $denied_file
99 | done
100 | miss_count=`awk '{print $1}' $denied_file | sort | uniq | wc -l`
101 |
102 | perf_data="total=${total};0;0 used=${used};0;0 missed_users=${miss_count};0;0"
103 | ;;
104 | esac
105 |
106 | done < $while_file
107 |
108 | rm -rf $random_file $denied_file $while_file
109 | echo "$msg | ${perf_data}"
110 | exit 0
111 |
--------------------------------------------------------------------------------
/nagios/pnp/check-cisco-cpu.php:
--------------------------------------------------------------------------------
1 |
34 |
--------------------------------------------------------------------------------
/nagios/pnp/check-cisco-fan.php:
--------------------------------------------------------------------------------
1 |
20 |
--------------------------------------------------------------------------------
/nagios/pnp/check-cisco-freeint.php:
--------------------------------------------------------------------------------
1 |
49 |
--------------------------------------------------------------------------------
/nagios/pnp/check-cisco-mem.php:
--------------------------------------------------------------------------------
1 |
20 |
--------------------------------------------------------------------------------
/nagios/pnp/check-cisco-module.php:
--------------------------------------------------------------------------------
1 |
20 |
--------------------------------------------------------------------------------
/nagios/pnp/check-cisco-ps.php:
--------------------------------------------------------------------------------
1 |
20 |
--------------------------------------------------------------------------------
/nagios/pnp/check-cisco-totalbw.php:
--------------------------------------------------------------------------------
1 |
38 |
--------------------------------------------------------------------------------
/nagios/pnp/check-juniper-vpn-load.php:
--------------------------------------------------------------------------------
1 |
34 |
--------------------------------------------------------------------------------
/nagios/pnp/check-juniper-vpn-mem.php:
--------------------------------------------------------------------------------
1 |
56 |
--------------------------------------------------------------------------------
/nagios/pnp/check-juniper-vpn-swap.php:
--------------------------------------------------------------------------------
1 |
40 |
--------------------------------------------------------------------------------
/nagios/pnp/check-pineapp-inout.php:
--------------------------------------------------------------------------------
1 |
38 |
--------------------------------------------------------------------------------
/nagios/pnp/check-pineapp-load.php:
--------------------------------------------------------------------------------
1 |
34 |
--------------------------------------------------------------------------------
/nagios/pnp/check-pineapp-queue.php:
--------------------------------------------------------------------------------
1 |
50 |
--------------------------------------------------------------------------------
/nagios/pnp/check_cpus_linux.php:
--------------------------------------------------------------------------------
1 | '#00CC00',
21 | 'nice' => '#000000',
22 | 'sys' => '#6600FF',
23 | 'system' => '#6600FF',
24 | 'iowait' => '#FF0000',
25 | 'irq' => '#663300',
26 | 'soft' => '#FFFF00',
27 | 'steal' => '#4596DD',
28 | 'idle' => '#4557DD',
29 | 'guest' => '#A445DD',
30 | 'idle' => '#66FFCC',
31 | );
32 |
33 |
34 | $current = 0;
35 | $var = 0;
36 |
37 | foreach ($DS as $i) {
38 | if($NAME[$i] == 'user' ) {
39 | $current = $i;
40 | $var = 1;
41 | $vlabel = "";
42 | if ($UNIT[$i] == "%%") {
43 | $vlabel = "%";
44 | }
45 | else {
46 | $vlabel = $UNIT[$i];
47 | }
48 |
49 | $opt[$current] = '--lower-limit 0 --upper-limit 100 --vertical-label "' . $vlabel . '" --title "' . $hostname . ' / ' . $servicedesc . '"' . $lower;
50 |
51 | $def[$current] = "DEF:var$var=$rrdfile:$DS[$i]:AVERAGE ";
52 | // $def[$current] .= "AREA:var$var" . _AREA . ":\"$NAME[$i] \" ";
53 | $def[$current] .= "LINE3:var$var" . $colors[$NAME[$i]] . ":\"$NAME[$i] \" ";
54 | $def[$current] .= "GPRINT:var$var:LAST:\"%3.4lf $UNIT[$i] LAST \" ";
55 | $def[$current] .= "GPRINT:var$var:MAX:\"%3.4lf $UNIT[$i] MAX \" ";
56 | $def[$current] .= "GPRINT:var$var:AVERAGE:\"%3.4lf $UNIT[$i] AVERAGE \\n\" ";
57 | } else {
58 | $var = $var + 1;
59 | $def[$current] .= "DEF:var$var=$rrdfile:$DS[$i]:AVERAGE ";
60 | $def[$current] .= "LINE3:var$var" . $colors[$NAME[$i]] . ":\"$NAME[$i] \" ";
61 | $def[$current] .= "GPRINT:var$var:LAST:\"%3.4lf $UNIT[$i] LAST \" ";
62 | $def[$current] .= "GPRINT:var$var:MAX:\"%3.4lf $UNIT[$i] MAX \" ";
63 | $def[$current] .= "GPRINT:var$var:AVERAGE:\"%3.4lf $UNIT[$i] AVERAGE \\n\" ";
64 | }
65 | }
66 | ?>
67 |
--------------------------------------------------------------------------------
/nagios/pnp/check_flexlm_new.php:
--------------------------------------------------------------------------------
1 |
20 |
--------------------------------------------------------------------------------
/nagios/pnp/check_load_srv.php:
--------------------------------------------------------------------------------
1 |
34 |
--------------------------------------------------------------------------------
/nagios/pnp/perf-ghs-float.php:
--------------------------------------------------------------------------------
1 |
31 |
--------------------------------------------------------------------------------
/nagios/pnp/perf-sge-cjs.php:
--------------------------------------------------------------------------------
1 |
68 |
--------------------------------------------------------------------------------
/nagios/pnp/perf-sge-qjs.php:
--------------------------------------------------------------------------------
1 |
44 |
--------------------------------------------------------------------------------
/zabbix/scripts/activemq-monitor.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | '''
4 | Monitor ActiveMQ server via its http web interface
5 | '''
6 |
7 | from HTMLParser import HTMLParser
8 | from optparse import OptionParser
9 | import xml.etree.ElementTree as ET
10 | import json
11 | import urllib2
12 | import urllib
13 |
14 | # Functions & Classes
15 | def prepareOpts():
16 | '''
17 | Parse option from the shell
18 | '''
19 |
20 | cmds = ['queue_prop', 'discovery', 'subscriber_exists']
21 | datas = ['size', 'consumerCount', 'enqueueCount', 'dequeueCount']
22 |
23 | def err( string ):
24 | print 'Error: {0}'.format( string )
25 | print __doc__
26 | parser.print_help()
27 | exit(1)
28 |
29 | parser = OptionParser()
30 | parser.add_option('-s', '--server', dest='server', type='string', help='ActiveMQ fqdn or ip', default='localhost')
31 | parser.add_option('-p', '--port', dest='port', type='int', help='ActiveMQ web interface port', default=8161)
32 | parser.add_option('-t', '--timeout', dest='timeout', type='float', help='how many seconds to wait for each http request', default=5)
33 | parser.add_option('-c', '--cmd', dest='cmd', type='choice', choices=cmds, help='what to check: {0}'.format(cmds) )
34 | parser.add_option('-q', '--queue', dest='queue', type='string', help='the name of the queue (implies -c queue_prop or -c subscriber_exists)')
35 | parser.add_option('-d', '--data', dest='data', type='choice', choices=datas, help='the name of the property to return {0} (implies -c queue_prop or -c subscriber_exists)'.format(datas) )
36 | parser.add_option('-C', '--client', dest='client', type='string', help='the client prefix to search (implies -c subscriber_exists and -q)' )
37 | (opts, args) = parser.parse_args()
38 |
39 |
40 | if not opts.cmd:
41 | err('missing -c')
42 |
43 | if opts.cmd == 'queue_prop' and (not opts.queue or not opts.data):
44 | err('missing -q or -d')
45 | elif opts.cmd == 'subscriber_exists' and ( not opts.queue or not opts.client ):
46 | err('missing -q or -C')
47 |
48 | return opts
49 |
50 | class ConsumerHTMLParser(HTMLParser):
51 | '''
52 | Parse the consumers id from http://url/admin/queueConsumers.jsp?JMSDestination=QUEUENAME
53 | '''
54 |
55 | consumers = []
56 | table = False
57 | body = False
58 | tr = False
59 | td = False
60 | a = False
61 |
62 | def reset_vars(self):
63 | self.consumers = []
64 | self.table = False
65 | self.body = False
66 | self.tr = False
67 | self.td = False
68 | self.a = False
69 |
70 | def handle_starttag(self, tag, attrs):
71 | if self.td and tag == 'a':
72 | self.a = True
73 | elif self.tr and tag == 'td':
74 | self.td = True
75 | elif self.body and tag == 'tr':
76 | self.tr = True
77 | elif self.table and tag == 'tbody':
78 | self.body = True
79 | elif tag == 'table':
80 | self.table = ('id', 'messages') in attrs
81 |
82 | def handle_data(self, data):
83 | if self.a:
84 | tmp = data.split('-')[0]
85 | if not tmp in self.consumers:
86 | self.consumers.append( tmp )
87 | self.a = False
88 | self.td = False
89 | self.tr = False
90 |
91 | def get_consumers(self):
92 | return self.consumers
93 |
94 |
95 | class ActivemqMonitor():
96 | '''
97 | Monitor ActiveMQ via http web interface
98 | '''
99 |
100 | def __init__(self, server, port, timeout):
101 | self.url = 'http://{0}:{1}'.format(server, port)
102 | self.server = server
103 | self.port = port
104 | self.timeout = timeout
105 |
106 | def discovery(self, **kwargs):
107 | '''
108 | return a json of all the queues in the server
109 | '''
110 | ret = {"data": []}
111 | for q in ET.fromstring( urllib2.urlopen(self.url+'/admin/xml/queues.jsp', timeout=self.timeout).read() ).findall('queue'):
112 | ret['data'].append( {
113 | '{#ACTIVEMQ_Q}': q.get('name')
114 | }
115 | )
116 | return ret
117 |
118 | def queue_prop(self, **kwargs):
119 | '''
120 | return the property of the queue in the server
121 | '''
122 | for q in ET.fromstring( urllib2.urlopen(self.url+'/admin/xml/queues.jsp', timeout=self.timeout).read() ).findall('queue'):
123 | if q.get('name') == kwargs['queue']:
124 | return int(q.find('stats').get(kwargs['data']))
125 |
126 | return 'couldnt find the queue'
127 |
128 | def subscriber_exists(self, **kwargs):
129 | '''
130 | check if the clientid is configured as a subscriber on the queue
131 | '''
132 |
133 | url = '{0}/admin/queueConsumers.jsp?{1}'.format(
134 | self.url,
135 | urllib.urlencode( { 'JMSDestination': kwargs['queue'] } ),
136 | )
137 | consumer_parser = ConsumerHTMLParser()
138 | consumer_parser.feed( urllib2.urlopen(url, timeout=self.timeout).read() )
139 |
140 | if kwargs['client'] in consumer_parser.get_consumers():
141 | return 1
142 | else:
143 | return 0
144 |
145 |
146 | # Global Settings
147 | opts = prepareOpts()
148 | monitor = ActivemqMonitor( opts.server, opts.port, opts.timeout )
149 | k = {
150 | 'queue': opts.queue,
151 | 'data': opts.data,
152 | 'client': opts.client,
153 | }
154 |
155 | # Do the work
156 | method = getattr(monitor, opts.cmd)
157 | res = method(**k)
158 | if type(res) is dict:
159 | print json.dumps( res )
160 | else:
161 | print res
162 |
--------------------------------------------------------------------------------
/zabbix/scripts/list_ips.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | Uses the zabbix python api to retrieve a list the all servers names & ips
4 |
5 | Need to configure the server, username & passwords settings
6 | '''
7 |
8 | from zabbix_api import ZabbixAPI
9 |
10 | server="https://url.of.zabbix.site"
11 | username="user of read on all hosts"
12 | password="pass"
13 |
14 | zapi = ZabbixAPI(server=server, path="")
15 | zapi.login(username, password)
16 |
17 | hosts=zapi.host.get({"selectInterfaces": "extend", "output": "extend"})
18 | for host in hosts:
19 | for int in host['interfaces']:
20 | print "{}\t{}".format(host['host'],host['interfaces'][int]['ip'])
21 | break
22 |
--------------------------------------------------------------------------------
/zabbix/scripts/rss.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python27
2 |
3 | '''
4 | Info:
5 | This python script is used as an Zabbix alert script to create simple RSS feed
6 | of the notifications
7 |
8 | To make it work:
9 | - Configure the Settings section in the script
10 | - add as an alert script in zabbix
11 | - notice that the subject won't be in the rss, only the message
12 | - add the xml code below to the rssFile
13 |
14 |
15 | en
16 |
17 |
18 | '''
19 |
20 | # libs
21 | import xml.etree.ElementTree as ET
22 | import datetime
23 | import sys
24 |
25 | # Settings
26 | link_data = "https://path/to/zabbix/tr_status.php?form_refresh=1&groupid=0&hostid=0&fullscreen=1"
27 | rssFile = "/path/to/zabbix/web/interface/rss"
28 | item_2_keep = 20
29 | title_data = sys.argv[3]
30 |
31 | # get root
32 | tree = ET.parse(rssFile)
33 | root = tree.getroot()
34 |
35 | # update time
36 | root[0][4].text = str(datetime.datetime.now())
37 |
38 | # add new item
39 | new_item = ET.SubElement(root[0],"item")
40 | title = ET.SubElement(new_item,"title")
41 | title.text = str(title_data)
42 | link = ET.SubElement(new_item,"link")
43 | link.text = str(link_data)
44 |
45 | # keep only x latest items
46 | itemRoot = root[0]
47 | items = itemRoot.findall('item')
48 | i=0
49 | for item in items:
50 | i=i+1
51 | if i > len(items)-item_2_keep:
52 | break
53 | itemRoot.remove(item)
54 |
55 |
56 | # write to file
57 | tree.write(rssFile)
58 |
--------------------------------------------------------------------------------
/zabbix/scripts/smx-bundle.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | '''
3 | Info:
4 | check via ssh if a bundle is in Active mode
5 | in an Apache ServiceMix setup
6 | '''
7 |
8 | import argparse
9 | import subprocess
10 | import re
11 |
12 | # Functions
13 | def myShell(cmd):
14 | """
15 | will execute the cmd in a Shell and will return the hash res
16 | res['out'] -> array of the stdout (bylines)
17 | res['err'] -> same as above only stderr
18 | res['exit'] -> the exit code of the command
19 | """
20 |
21 | res = {}
22 | proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=None)
23 | tmp = proc.communicate()
24 | res['out'] = tmp[0].splitlines()
25 | res['err'] = tmp[1].splitlines()
26 | res['exit'] = proc.returncode
27 | return res
28 |
29 |
30 | # Parser
31 | parser = argparse.ArgumentParser(description="check via ssh-smx if the bundle is in Active mode in an Apache ServiceMix setup")
32 | parser.add_argument("srv", type=str, help="hostname or ip of the smx server")
33 | parser.add_argument("port", type=int, help="port of the smx daemon")
34 | parser.add_argument("user", type=str, help="servicemix username")
35 | parser.add_argument("passwd", type=str, help="servicemix password")
36 | parser.add_argument("bundle", type=str, help="bundle name")
37 | args = parser.parse_args()
38 |
39 | # Settings
40 | ssh = "timeout 3 sshpass -p "+str(args.passwd)+" ssh -l "+str(args.user)+" -o ConnectTimeout=3 -o StrictHostKeyChecking=no -p "+str(args.port)+" "+args.srv+" osgi:list"
41 |
42 | # Start script
43 | output = myShell(ssh)
44 | if output['exit'] != 0:
45 | print 0
46 | exit(1)
47 |
48 | output['out'].pop(0)
49 | output['out'].pop(0)
50 |
51 | found = False
52 | for line in output['out']:
53 | if re.search('\[Active', line):
54 | linePars = line.split("]")
55 | name = linePars.pop()
56 | name.strip()
57 | if re.search(re.escape(args.bundle), name):
58 | found = True
59 | break
60 |
61 | if found:
62 | print 1
63 | else:
64 | print 0
65 |
66 |
--------------------------------------------------------------------------------
/zabbix/scripts/solr.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | '''
4 | Monitor Apache Solr via HTTP for Zabbix
5 | '''
6 |
7 | from optparse import OptionParser
8 | import xml.etree.ElementTree as ET
9 | import urllib2
10 |
11 |
12 | def prepareOpts():
13 | '''
14 | Parse option from the shell
15 | '''
16 |
17 | cmds = [
18 | 'ping',
19 | 'dataimportDocumentsProcessed',
20 | 'indexBehindMaster'
21 | ]
22 |
23 | def err( string ):
24 | print 'Error: {0}'.format( string )
25 | parser.print_help()
26 | print __doc__
27 | exit(1)
28 |
29 | parser = OptionParser()
30 | parser.add_option('-u', '--url', dest='url', type='string', help='solr url', default=None)
31 | parser.add_option('-U', '--user', dest='user', type='string', help='username', default=None)
32 | parser.add_option('-P', '--passwd', dest='passwd', type='string', help='password', default=None)
33 | parser.add_option('-t', '--timeout', dest='timeout', type='float', help='how many seconds to wait for each http request', default=5)
34 | parser.add_option('-c', '--cmd', dest='cmd', type='choice', choices=cmds, help='what to check: {0}'.format(cmds) )
35 | parser.add_option('-C', '--core', dest='core', type='string', help='core id', default=None)
36 | parser.add_option('-H', '--handler', dest='handler', type='string', help='dataimport handler name', default=None)
37 | (opts, args) = parser.parse_args()
38 |
39 | if not opts.cmd:
40 | err('missing -c')
41 | if (opts.user and not opts.passwd) or (not opts.user and opts.passwd):
42 | err('missing username or password')
43 | if not opts.url:
44 | err('missing solr http url')
45 | if opts.cmd == 'dataimportDocumentsProcessed':
46 | if opts.core is None:
47 | err('missing core id !')
48 | if opts.handler is None:
49 | err('missing handler name !')
50 |
51 | return opts
52 |
53 |
54 | class SolrMonitor():
55 | '''
56 | Monitor Apache Solr via http
57 | '''
58 |
59 | def __init__(self, url, timeout=5, username=None, passwd=None):
60 | self.url = url
61 | self.timeout = timeout
62 | self.username = username
63 | self.passwd = passwd
64 |
65 | if self.url.endswith('/'):
66 | self.url = self.url[:-1]
67 |
68 | self._get_auth()
69 |
70 | def _get_auth(self):
71 | '''
72 | Build an Auth opener for HTTP connection
73 | '''
74 | if not self.username or not self.passwd:
75 | return
76 | basic = urllib2.HTTPBasicAuthHandler()
77 | basic.add_password(
78 | realm='Solr',
79 | uri=self.url,
80 | user=self.username,
81 | passwd=self.passwd
82 | )
83 | digest = urllib2.HTTPDigestAuthHandler()
84 | digest.add_password(
85 | realm='Solr',
86 | uri=self.url,
87 | user=self.username,
88 | passwd=self.passwd
89 | )
90 |
91 | urllib2.install_opener(
92 | urllib2.build_opener(basic, digest))
93 |
94 | def _getXmlData(self, url):
95 | '''
96 | create an http request to url and return the data
97 | in case of a problem return None
98 | '''
99 |
100 | try:
101 | return ET.fromstring(
102 | urllib2.urlopen(
103 | url,
104 | timeout=self.timeout
105 | ).read()
106 | )
107 | except urllib2.URLError:
108 | return None
109 |
110 | def ping(self):
111 | '''
112 | Check if solr ping returns True
113 | '''
114 |
115 | ret = 0
116 | root = self._getXmlData(self.url + '/admin/ping')
117 | if root is None:
118 | return 0
119 |
120 | if root.find('str').text == 'OK':
121 | ret = 1
122 |
123 | return ret
124 |
125 | def dataimportDocumentsProcessed(self, core, handler):
126 | '''
127 | Return the number of processed documents
128 | from the dataimport handler
129 |
130 | url: http://solr:port/solr/core0/dataimportName?command=status
131 | '''
132 |
133 | url = '{0}/{1}/{2}?command=status'.format(
134 | self.url,
135 | core,
136 | handler
137 | )
138 | root = self._getXmlData(url)
139 | if root is None:
140 | return -1
141 |
142 | for lst in root.findall('lst'):
143 | if lst.attrib['name'] == 'statusMessages':
144 | for str in lst.findall('str'):
145 | if str.attrib['name'] == 'Total Documents Processed':
146 | return int(str.text)
147 |
148 | return -1
149 |
150 | # Python 2.7
151 | # return int(
152 | # root.findall(
153 | # "lst[@name='statusMessages']/str[@name='Total Documents Processed']"
154 | # )[0].text
155 | # )
156 |
157 | def indexBehindMaster(self):
158 | '''
159 | Returns the difference bewteen the slave index
160 | and the master replicable index
161 | '''
162 |
163 | slave = None
164 | master = None
165 | root = self._getXmlData(
166 | self.url + '/replication?command=details'
167 | )
168 | if root is None:
169 | return -1
170 |
171 | for lst in root.findall('lst'):
172 | if lst.attrib['name'] == 'details':
173 |
174 | # Slave
175 | for lng in lst.findall('long'):
176 | if lng.attrib['name'] == 'indexVersion':
177 | slave = long(lng.text)
178 | break
179 |
180 | # Master
181 | for lstm in lst.findall('lst'):
182 | if lstm.attrib['name'] == 'slave':
183 | for lstms in lstm.findall('lst'):
184 | if lstms.attrib['name'] == 'masterDetails':
185 | for lstMaster in lstms.findall('lst'):
186 | if lstMaster.attrib['name'] == 'master':
187 | for rep in lstMaster.findall('long'):
188 | if rep.attrib['name'] == 'replicableVersion':
189 | master = long(rep.text)
190 | break
191 |
192 | if master and slave:
193 | break
194 |
195 | # Python 2.7
196 | # slave = root.findall(
197 | # "./*[@name='details']/arr[@name='commits']/lst/long[@name='indexVersion']"
198 | # )[0].text
199 | # master = root.findall(
200 | # "./lst[@name='details']/lst[@name='slave']/lst[@name='masterDetails']/lst[@name='master']/long[@name='replicableVersion']"
201 | # )[0].text
202 | return long(master - slave)
203 |
204 | @staticmethod
205 | def main():
206 | '''
207 | Main function
208 | '''
209 |
210 | opts = prepareOpts()
211 | solr = SolrMonitor( opts.url, opts.timeout, opts.user, opts.passwd )
212 |
213 | method = getattr(solr, opts.cmd)
214 | k = {}
215 | if opts.core:
216 | k.update({'core': opts.core})
217 | if opts.handler:
218 | k.update({'handler': opts.handler})
219 | print method(**k)
220 |
221 |
222 | if __name__ == '__main__':
223 | SolrMonitor.main()
224 |
--------------------------------------------------------------------------------
/zabbix/user_param/apache.conf:
--------------------------------------------------------------------------------
1 | ####################
2 | ### Apache HTTPD ###
3 | ####################
4 | # get data from mod_status
5 | # $1 - Variable name
6 | UserParameter=apache.server-status[*],data=$(wget --no-check-certificate http://localhost/server-status?auto -O - -q --timeout=3 -t 1 | grep ^"$1:" | awk '{print $NF}') ; [ "$data" == "" ] && data=0 ; echo $data | sed 's/^\./0./'
7 | # count a scoreboard status from mod_status
8 | # $1 :
9 | # "_" Waiting for Connection
10 | # "S" Starting up
11 | # "R" Reading Request
12 | # "W" Sending Reply
13 | # "K" Keepalive (read)
14 | # "D" DNS Lookup
15 | # "C" Closing connection
16 | # "L" Logging
17 | # "G" Gracefully finishing,
18 | # "I" Idle cleanup of worker
19 | # "." Open slot with no current process
20 | UserParameter=apache.scoreboard[*],wget --no-check-certificate http://localhost/server-status?auto -O - -q --timeout=3 -t 1 | grep ^Scoreboard: | awk '{print $NF}' | grep -o '\'$1 | wc -l
21 |
22 |
--------------------------------------------------------------------------------
/zabbix/user_param/fs_discovery.conf:
--------------------------------------------------------------------------------
1 | ##########################
2 | ### / & /mnt Discovery ###
3 | ##########################
4 | UserParameter=mount.discovery,echo { \"data\":[ { \"{#MOUNT_NAME}\":\"\\/\", \"{#MOUNT_DEVICE}\":\"$(df / | sed -n '2p' | awk '{print $1}' | sed 's/\//\\\//g')\" }, { \"{#MOUNT_NAME}\":\"\\/mnt\", \"{#MOUNT_DEVICE}\":\"$(df /mnt | sed -n '2p' | awk '{print $1}' | sed 's/\//\\\//g')\" } ] }
5 |
6 |
--------------------------------------------------------------------------------
/zabbix/user_param/mysql.conf:
--------------------------------------------------------------------------------
1 | ####################
2 | ### MySQL Server ###
3 | ####################
4 | # GRANT SELECT ON *.* TO zabbix@localhost IDENTIFIED BY '*******';
5 | # 1 - user
6 | # 2 - password
7 | UserParameter=mysql.com_select[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Com_select';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
8 | UserParameter=mysql.qcache_hits[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Qcache_hits';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
9 | UserParameter=mysql.threads_connected[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Threads_connected';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
10 | UserParameter=mysql.table_locks_waited[*],data=$(mysql--connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Table_locks_waited';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
11 | UserParameter=mysql.created_tmp_tables[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Created_tmp_tables';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
12 | UserParameter=mysql.created_tmp_disk_tables[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Created_tmp_disk_tables';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
13 | UserParameter=mysql.slow_queries[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Slow_queries';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
14 | UserParameter=mysql.aborted_connects[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Aborted_connects';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
15 | UserParameter=mysql.innodb_buffer_pool_read_requests[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Innodb_buffer_pool_read_requests';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
16 | UserParameter=mysql.innodb_buffer_pool_reads[*],data=$(mysql --connect_timeout 2 -N -u $1 -p$2 -e "SHOW GLOBAL STATUS where Variable_name = 'Innodb_buffer_pool_reads';" 2> /dev/null | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
17 | UserParameter=mysql.slave_io_running[*],mysql --connect_timeout 2 -u $1 -p$2 -e "SHOW SLAVE STATUS\G;" 2> /dev/null | sed '1d' |grep Slave_IO_Running | awk '{print $NF}' | grep -c Yes
18 | UserParameter=mysql.slave_sql_running[*],mysql --connect_timeout 2 -u $1 -p$2 -e "SHOW SLAVE STATUS\G;" 2> /dev/null | sed '1d' |grep Slave_SQL_Running | awk '{print $NF}' | grep -c Yes
19 | UserParameter=mysql.seconds_behind_master[*],data=$(mysql --connect_timeout 2 -u $1 -p$2 -e "SHOW SLAVE STATUS\G;" 2> /dev/null | sed '1d' |grep Seconds_Behind_Master | awk '{print $NF}') ; [ -z "$data" ] && data=0 ; echo $data
20 | UserParameter=mysql.slave_io_last_error[*],msg=$(mysql --connect_timeout 2 -u $1 -p$2 -e "SHOW SLAVE STATUS\G;" 2> /dev/null | sed '1d' | grep Last_IO_Error: | sed 's/\s*Last_IO_Error: //g') ; [ -z "$msg" ] && msg="-1" ; echo $msg
21 | UserParameter=mysql.slave_sql_last_error[*],msg=$(mysql --connect_timeout 2 -u $1 -p$2 -e "SHOW SLAVE STATUS\G;" 2> /dev/null | sed '1d' | grep Last_SQL_Error: | sed 's/\s*Last_SQL_Error: //g') ; [ -z "$msg" ] && msg="-1" ; echo $msg
22 |
--------------------------------------------------------------------------------
/zabbix/user_param/solr.conf:
--------------------------------------------------------------------------------
1 | ############
2 | ### Solr ###
3 | ############
4 | UserParameter=solr.ping[*],wget -q -O - --timeout=3 -t 1 $1/admin/ping 2> /dev/null | grep -c "OK"
5 | UserParameter=solr.slave_up[*],wget -q -O - --timeout=3 -t 1 $1/admin/replication/index.jsp 2> /dev/null |grep -A 3 'Master' | tail -n 1 | sed 's/\s//g' | wc -l
6 | UserParameter=solr.slave_index_behind_master[*],out=$(expr $(echo $( wget $1/admin/replication/index.jsp -q -O - --timeout=3 -t 1 2> /dev/null |grep 'Index Version:' | grep -v 'Latest' | awk '{print $$3}' | grep -E -o "[0-9]+") | sed 's/\ /\ -\ /g' )) ; [ -z "$out" ] && out=0 ; echo $out
7 | UserParameter=solr.docs_indexing[*],docs=$(wget $1/dataimport -q -O - --timeout=3 -t 1 2> /dev/null | grep -o '[0-9]*' | sed -e 's///g' -e 's/<\/str>//g') ; [ -z "$docs" ] && docs=0 ; echo $docs
8 |
9 |
--------------------------------------------------------------------------------