├── .gitignore ├── .project ├── .pydevproject ├── .settings └── org.eclipse.core.resources.prefs ├── LICENSE ├── README.md ├── check_elasticsearch.py ├── check_httpd.sh ├── check_ifstat.sh ├── check_internal_ping.sh ├── check_iostat.sh ├── check_mem.sh ├── check_nbhao.sh ├── check_net_traffic.sh ├── check_nfs.sh ├── check_nowsms.py ├── check_pgbouncer.sh ├── check_pglag.sh ├── check_postgresql.sh ├── check_pptp.sh ├── check_shadowsocks.sh ├── check_sms.sh ├── check_speed.sh ├── check_tcp_stat.sh ├── check_tomcat_log.sh ├── check_tp_er5120.py ├── pnp4nagios ├── check_mem.php ├── check_net_traffic.php ├── check_nowsms.php └── check_tcp_stat.php ├── setup ├── nagios │ ├── centos-pnp4nagios.sh │ ├── centos6-nagios-server.sh │ ├── php │ │ └── ubuntu_php.sh │ ├── setupinit.sh │ └── ubuntu.sh ├── nagios_client │ ├── centos.sh │ └── ubuntu.sh ├── submit_host_check_result └── submit_service_check_result └── weixin ├── NotifyByWeixin.py ├── README.md └── config-sample.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | logs/* 6 | videos/* 7 | 8 | weixin/config.py 9 | weixin/token_data.pkl 10 | 11 | .settings/* -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nagios 4 | 5 | 6 | 7 | 8 | 9 | org.python.pydev.PyDevBuilder 10 | 11 | 12 | 13 | 14 | 15 | org.python.pydev.pythonNature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.pydevproject: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /${PROJECT_DIR_NAME} 5 | 6 | python 2.7 7 | Default 8 | 9 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//weixin/NotifyByWeixin.py=utf-8 3 | encoding//weixin/config-sample.py=utf-8 4 | encoding//weixin/config.py=utf-8 5 | encoding/check_elasticsearch.py=utf-8 6 | encoding/check_nowsms.py=utf-8 7 | encoding/check_tp_er5120.py=utf-8 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nagios 2 | nagios一键安装脚本和插件脚本 3 | 4 | ##一键安装脚本 5 | 6 | ###服务端 7 | 8 | Ubuntu&Debian: 9 | 10 | 安装脚本:setup/nagios/ubuntu.sh 11 | 12 | 脚本会自动安装apache,php,nagios和pnp4nagios 13 | 14 | CentOS: 15 | 16 | 安装脚本:setup/nagios/centos6-nagios-server.sh 17 | 18 | 脚本会自动安装apache,php和nagios 19 | 20 | php4nagios安装脚本:setup/nagios/centos-pnp4nagios.sh 21 | 22 | ###客户端 23 | 24 | 客户端安装nrpe 25 | 26 | ubuntu&debian:setup/nagios_client/ubuntu.sh 27 | 28 | centos:setup/nagios_client/centos.sh 29 | 30 | ##插件脚本 31 | 32 | aaa 33 | -------------------------------------------------------------------------------- /check_elasticsearch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | import urllib2 5 | import sys 6 | import argparse 7 | import json 8 | import base64 9 | 10 | parser=argparse.ArgumentParser(description="check elastic search health.") 11 | parser.add_argument("-H",dest="host",help="Host") 12 | parser.add_argument("-P",dest="port",default=9200,help="elastic search http port,default 9200.") 13 | parser.add_argument("-u",dest="username",default=None,help="http auth username") 14 | parser.add_argument("-p",dest="password",default=None,help="http auth password") 15 | 16 | args=parser.parse_args() 17 | 18 | if not args.host or not args.port: 19 | print "Critical - Invalid command,please check." 20 | sys.exit(2) 21 | 22 | 23 | url='http://%s:%s/_cluster/health' % (args.host,args.port) 24 | req=urllib2.Request(url) 25 | if args.username and args.password: 26 | base64string = base64.b64encode('%s:%s' % (args.username,args.password)) 27 | req.add_header("Authorization", "Basic %s" % base64string) 28 | 29 | req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36") 30 | 31 | try: 32 | response=urllib2.urlopen(req,timeout=30) 33 | except urllib2.HTTPError,e: 34 | print "Critical - %s" % e 35 | sys.exit(2) 36 | except: 37 | print "Critical - elasticsearch health status get error." 38 | sys.exit(2) 39 | 40 | result=json.loads(response.read()) 41 | 42 | if result['status'] == 'green': 43 | print "OK - elasticsearch is running,status: green. | active_primary=%s;;;;active=%s;;;;relocating=%s;;;;init=%s;;;;" % \ 44 | (result['active_primary_shards'],result['active_shards'],result['relocating_shards'],result['initializing_shards']) 45 | sys.exit(0) 46 | elif result['status'] == 'yellow': 47 | print "WARNING - elasticsearch is running,status: yellow. | active_primary=%s;;;;active=%s;;;;relocating=%s;;;;init=%s;;;;" % \ 48 | (result['active_primary_shards'],result['active_shards'],result['relocating_shards'],result['initializing_shards']) 49 | sys.exit(1) 50 | else: 51 | print "Critical - elasticsearch is running,status: red. | active_primary=%s;;;;active=%s;;;;relocating=%s;;;;init=%s;;;;" % \ 52 | (result['active_primary_shards'],result['active_shards'],result['relocating_shards'],result['initializing_shards']) 53 | sys.exit(2) 54 | 55 | -------------------------------------------------------------------------------- /check_httpd.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 4 | 5 | #ajp_ilink_receive timeout 6 | error_log_path=/usr/local/apache2/logs/error_log 7 | num=20 8 | 9 | year=`date "+%Y"` 10 | day=`date "+%d"` 11 | hour=`date "+%H"` 12 | err_cnt=`tail -n $num $error_log_path|grep "$day $hour:[0-9]*:[0-9]* $year] .* ajp_ilink_receive"|grep -cv grep` 13 | let ratio=($err_cnt*100)/$num 14 | if [ $ratio -gt 80 ];then 15 | echo "Critical - apache ajp receive timeout,ratio ${ratio}%." 16 | exit 2 17 | fi 18 | if [ $ratio -gt 60 ];then 19 | echo "Warning - apache ajp receive timeout,ratio ${ratio}%." 20 | exit 1 21 | fi 22 | 23 | #process 24 | mpm_config_path=/usr/local/apache2/conf/extra/httpd-mpm.conf 25 | max_cnt=`grep mpm_prefork_module $mpm_config_path -A 8|grep MaxClients|awk '{print $NF}'` 26 | now_cnt=`ps -ef|grep '/usr/local/apache2/bin/httpd -k start'|grep -cv grep` 27 | 28 | if [ $now_cnt -eq 0 ];then 29 | echo "Critical - apache httpd is stoped." 30 | exit 2 31 | fi 32 | 33 | let ratio=($now_cnt*100)/$max_cnt 34 | if [ $ratio -gt 90 ];then 35 | echo "Critical - apache process count is $now_cnt,ratio ${ratio}%." 36 | exit 2 37 | fi 38 | if [ $ratio -gt 70 ];then 39 | echo "Warning - apache process count is $now_cnt,ratio ${ratio}%." 40 | exit 1 41 | fi 42 | 43 | #ok 44 | echo "OK - apache is running ok.|process=$now_cnt;;;;" 45 | exit 0 -------------------------------------------------------------------------------- /check_ifstat.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #example 4 | #command[check_eth0_ifstat]=/usr/local/nagios/libexec/custom/check_ifstat.sh eth0 5 | 6 | a=$1 7 | 8 | #define status 9 | STATE_OK=0 10 | STATE_WARNING=1 11 | STATE_CRITICAL=2 12 | 13 | w_if=102400 14 | c_if=102400 15 | 16 | STATIN=`/usr/bin/ifstat -i $a 3 1 | sed -n '3p' |awk '{print $1}'| cut -f 1 -d "."` 17 | STATOUT=`/usr/bin/ifstat -i $a 3 1 | sed -n '3p' |awk '{print $2}'| cut -f 1 -d "."` 18 | if [ $STATIN -gt $c_if ]||[ $STATOUT -gt $c_if ] 19 | then 20 | echo "CRITICAL - INPUT=$STATIN KB/s,OUTPUT=$STATOUT KB/s. | INPUT=$STATIN;$w_if;$c_if;;OUTPUT=$STATOUT;$w_if;$c_if;;" 21 | exit $STATE_CRITICAL 22 | fi 23 | if ([ $STATIN -gt $w_if ] && [ $STATIN -lt $c_if ])|| ([ $STATOUT -gt $w_if ] && [ $STATOUT -lt $c_if ]) 24 | then 25 | echo "WARNING - INPUT=$STATIN KB/s,OUTPUT=$STATOUT KB/s. | INPUT=$STATIN;$w_if;$c_if;;OUTPUT=$STATOUT;$w_if;$c_if;;" 26 | exit $STATE_WARNING 27 | fi 28 | echo "OK - INPUT=$STATIN KB/s,OUTPUT=$STATOUT KB/s. | INPUT=$STATIN;$w_if;$c_if;;OUTPUT=$STATOUT;$w_if;$c_if;;" 29 | exit $STATE_OK 30 | -------------------------------------------------------------------------------- /check_internal_ping.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ################################## 4 | # 5 | ####nagios监控脚本 6 | ####作者:章郎虫 7 | ####博客:http://www.sijitao.net/ 8 | # 9 | ####ping.sh脚本 10 | for ip in `seq 101 110` 11 | do 12 | ping -c 1 192.168.1.$ip |awk 'NR==2{print $3}' |while read from 13 | do 14 | if [ "$from"x != "from"x ];then 15 | echo "192.168.1.$ip" >/tmp/ping.log 16 | fi 17 | done 18 | done 19 | ################################## 20 | 21 | #define status 22 | STATE_OK=0 23 | STATE_WARNING=1 24 | STATE_CRITICAL=2 25 | 26 | cd /tmp 27 | state="ok" 28 | 29 | for state in `cat ping.log` 30 | do 31 | 32 | if [ "$state"x != ""x ];then 33 | echo "CRITICAL - $state is down!" 34 | exit $STATE_CRITICAL 35 | fi 36 | done 37 | 38 | if [ "$state"x = "ok"x ];then 39 | echo "OK - All internal servers is uptime!" 40 | exit $STATE_OK 41 | fi 42 | -------------------------------------------------------------------------------- /check_iostat.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | #http://exchange.nagios.org/directory/Plugins/Operating-Systems/Linux/check_iostat--2D-I-2FO-statistics/details 4 | #----------check_iostat.sh----------- 5 | # 6 | # Version 0.0.2 - Jan/2009 7 | # Changes: added device verification 8 | # 9 | # by Thiago Varela - thiago@iplenix.com 10 | # 11 | # Version 0.0.3 - Dec/2011 12 | # Changes: 13 | # - changed values from bytes to mbytes 14 | # - fixed bug to get traffic data without comma but point 15 | # - current values are displayed now, not average values (first run of iostat) 16 | # 17 | # by Philipp Niedziela - pn@pn-it.com 18 | # 19 | # Version 0.0.4 - April/2014 20 | # Changes: 21 | # - Allow Empty warn/crit levels 22 | # - Can check I/O, WAIT Time, or Queue 23 | # 24 | # by Warren Turner 25 | # 26 | # Version 0.0.5 - Jun/2014 27 | # Changes: 28 | # - removed -y flag from call since iostat doesn't know about it any more (June 2014) 29 | # - only needed executions of iostat are done now (save cpu time whenever you can) 30 | # - fixed the obvious problems of missing input values (probably because of the now unimplemented "-y") with -x values 31 | # - made perfomance data optional (I like to have choice in the matter) 32 | # 33 | # by Frederic Krueger / fkrueger-dev-checkiostat@holics.at 34 | # 35 | # Version 0.0.6 - Jul/2014 36 | # Changes: 37 | # - Cleaned up argument checking, removed excess iostat calls, steamlined if statements and renamed variables to fit current use 38 | # - Fixed all inputs to match current iostat output (Ubuntu 12.04) 39 | # - Changed to take last ten seconds as default (more useful for nagios usage). Will go to "since last reboot" (previous behaviour) on -g flag. 40 | # - added extra comments/whitespace etc to make add readability 41 | # 42 | # by Ben Field / ben.field@concreteplatform.com 43 | # 44 | # Version 0.0.7 - Sep/2014 45 | # Changes: 46 | # - Fixed performance data for Wait check 47 | # 48 | # by Christian Westergard / christian.westergard@gmail.com 49 | # 50 | 51 | 52 | iostat=`which iostat 2>/dev/null` 53 | bc=`which bc 2>/dev/null` 54 | 55 | function help { 56 | echo -e " 57 | Usage: 58 | 59 | -d = 60 | --Device to be checked. Example: \"-d sda\" 61 | 62 | Run only one of i, q, W: 63 | 64 | -i = IO Check Mode 65 | --Checks Total Transfers/sec, Read IO/Sec, Write IO/Sec, Bytes Read/Sec, Bytes Written/Sec 66 | --warning/critical = Total Transfers/sec,Read IO/Sec,Write IO/Sec,Bytes Read/Sec,Bytes Written/Sec 67 | 68 | -q = Queue Mode 69 | --Checks Disk Queue Lengths 70 | --warning/critial = Average size of requests, Queue length of requests 71 | 72 | -W = Wait Time Mode 73 | --Check the time for I/O requests issued to the device to be served. This includes the time spent by the requests in queue and the time spent servicing them. 74 | --warning/critical = Avg I/O Wait Time (ms), Avg Read Wait Time (ms), Avg Write Wait Time (ms), Avg Service Wait Time (ms), Avg CPU Utilization 75 | 76 | -w,-c = pass warning and critical levels respectively. These are not required, but with out them, all queries will return as OK. 77 | 78 | -p = Provide performance data for later graphing 79 | 80 | -g = Since last reboot for system (more for debugging that nagios use!) 81 | 82 | -h = This help 83 | " 84 | exit -1 85 | } 86 | 87 | # Ensuring we have the needed tools: 88 | ( [ ! -f $iostat ] || [ ! -f $bc ] ) && \ 89 | ( echo "ERROR: You must have iostat and bc installed in order to run this plugin\n\tuse: apt-get install systat bc\n" && exit -1 ) 90 | 91 | io=0 92 | queue=0 93 | waittime=0 94 | printperfdata=0 95 | STATE="OK" 96 | samples=2i 97 | status=0 98 | 99 | MSG="" 100 | PERFDATA="" 101 | 102 | #------------Argument Set------------- 103 | 104 | while getopts "d:w:c:ipqWhg" OPT; do 105 | case $OPT in 106 | "d") disk=$OPTARG;; 107 | "w") warning=$OPTARG;; 108 | "c") critical=$OPTARG;; 109 | "i") io=1;; 110 | "p") printperfdata=1;; 111 | "q") queue=1;; 112 | "W") waittime=1;; 113 | "g") samples=1;; 114 | "h") echo "help:" && help;; 115 | \?) echo "Invalid option: -$OPTARG" >&2 116 | exit -1 117 | ;; 118 | esac 119 | done 120 | 121 | # Autofill if parameters are empty 122 | if [ -z "$disk" ] 123 | then disk=sda 124 | fi 125 | 126 | #Checks that only one query type is run 127 | [[ `expr $io+$queue+$waittime` -ne "1" ]] && \ 128 | echo "ERROR: select one and only one run mode" && help 129 | 130 | #set warning and critical to insane value is empty, else set the individual values 131 | if [ -z "$warning" ] 132 | then warning=99999 133 | else 134 | #TPS with IO, Request size with queue 135 | warn_1=`echo $warning | cut -d, -f1` 136 | #Read/s with IO,Queue Length with queue 137 | warn_2=`echo $warning | cut -d, -f2` 138 | #Write/s with IO 139 | warn_3=`echo $warning | cut -d, -f3` 140 | #KB/s read with IO 141 | warn_4=`echo $warning | cut -d, -f4` 142 | #KB/s written with IO 143 | warn_5=`echo $warning | cut -d, -f5` 144 | #Crude hack due to integer expression later in the script 145 | warning=1 146 | fi 147 | 148 | if [ -z "$critical" ] 149 | then critical=99999 150 | else 151 | #TPS with IO, Request size with queue 152 | crit_1=`echo $critical | cut -d, -f1` 153 | #Read/s with IO,Queue Length with queue 154 | crit_2=`echo $critical | cut -d, -f2` 155 | #Write/s with IO 156 | crit_3=`echo $critical | cut -d, -f3` 157 | #KB/s read with IO 158 | crit_4=`echo $critical | cut -d, -f4` 159 | #KB/s written with IO 160 | crit_5=`echo $critical | cut -d, -f5` 161 | #Crude hack due to integer expression later in the script 162 | critical=1 163 | fi 164 | 165 | #------------Argument Set End------------- 166 | 167 | #------------Parameter Check------------- 168 | 169 | #Checks for sane Disk name: 170 | [ ! -b "/dev/$disk" ] && echo "ERROR: Device incorrectly specified" && help 171 | 172 | #Checks for sane warning/critical levels 173 | if ( [[ $warning -ne "99999" ]] || [[ $critical -ne "99999" ]] ); then 174 | if ( [[ "$warn_1" -gt "$crit_1" ]] || [[ "$warn_2" -gt "$crit_2" ]] ); then 175 | echo "ERROR: critical levels must be higher than warning levels" && help 176 | elif ( [[ $io -eq "1" ]] || [[ $waittime -eq "1" ]] ); then 177 | if ( [[ "$warn_3" -gt "$crit_3" ]] || [[ "$warn_4" -gt "$crit_4" ]] || [[ "$warn_5" -gt "$crit_5" ]] ); then 178 | echo "ERROR: critical levels must be higher than warning levels" && help 179 | fi 180 | fi 181 | fi 182 | 183 | #------------Parameter Check End------------- 184 | 185 | # iostat parameters: 186 | # -m: megabytes 187 | # -k: kilobytes 188 | # first run of iostat shows statistics since last reboot, second one shows current vaules of hdd 189 | # -d is the duration for second run, -x the rest 190 | 191 | TMPX=`$iostat $disk -x -k -d 10 $samples | grep $disk | tail -1` 192 | 193 | #------------IO Test------------- 194 | 195 | if [ "$io" == "1" ]; then 196 | 197 | TMPD=`$iostat $disk -k -d 10 $samples | grep $disk | tail -1` 198 | #Requests per second: 199 | tps=`echo "$TMPD" | awk '{print $2}'` 200 | read_sec=`echo "$TMPX" | awk '{print $4}'` 201 | written_sec=`echo "$TMPX" | awk '{print $5}'` 202 | 203 | #Kb per second: 204 | kbytes_read_sec=`echo "$TMPX" | awk '{print $6}'` 205 | kbytes_written_sec=`echo "$TMPX" | awk '{print $7}'` 206 | 207 | # "Converting" values to float (string replace , with .) 208 | tps=${tps/,/.} 209 | read_sec=${read_sec/,/.} 210 | written_sec=${written_sec/,/.} 211 | kbytes_read_sec=${kbytes_read_sec/,/.} 212 | kbytes_written_sec=${kbytes_written_sec/,/.} 213 | 214 | # Comparing the result and setting the correct level: 215 | if [ "$warning" -ne "99999" ]; then 216 | if ( [ "`echo "$tps >= $warn_1" | bc`" == "1" ] || [ "`echo "$read_sec >= $warn_2" | bc`" == "1" ] || \ 217 | [ "`echo "$written_sec >= $warn_3" | bc`" == "1" ] || [ "`echo "$kbytes_read_sec >= $warn_4" | bc -q`" == "1" ] || 218 | [ "`echo "$kbytes_written_sec >= $warn_5" | bc`" == "1" ] ); then 219 | STATE="WARNING" 220 | status=1 221 | fi 222 | fi 223 | if [ "$critical" -ne "99999" ]; then 224 | if ( [ "`echo "$tps >= $crit_1" | bc`" == "1" ] || [ "`echo "$read_sec >= $crit_2" | bc -q`" == "1" ] || \ 225 | [ "`echo "$written_sec >= $crit_3" | bc`" == "1" ] || [ "`echo "$kbytes_read_sec >= $crit_4" | bc -q`" == "1" ] || \ 226 | [ "`echo "$kbytes_written_sec >= $crit_5" | bc`" == "1" ] ); then 227 | STATE="CRITICAL" 228 | status=2 229 | fi 230 | fi 231 | # Printing the results: 232 | MSG="$STATE - I/O stats: Transfers/Sec=$tps Read Requests/Sec=$read_sec Write Requests/Sec=$written_sec KBytes Read/Sec=$kbytes_read_sec KBytes_Written/Sec=$kbytes_written_sec" 233 | PERFDATA=" | total_io_sec'=$tps; read_io_sec=$read_sec; write_io_sec=$written_sec; kbytes_read_sec=$kbytes_read_sec; kbytes_written_sec=$kbytes_written_sec;" 234 | fi 235 | 236 | #------------IO Test End------------- 237 | 238 | #------------Queue Test------------- 239 | if [ "$queue" == "1" ]; then 240 | qsize=`echo "$TMPX" | awk '{print $8}'` 241 | qlength=`echo "$TMPX" | awk '{print $9}'` 242 | 243 | # "Converting" values to float (string replace , with .) 244 | qsize=${qsize/,/.} 245 | qlength=${qlength/,/.} 246 | 247 | # Comparing the result and setting the correct level: 248 | if [ "$warning" -ne "99999" ]; then 249 | if ( [ "`echo "$qsize >= $warn_1" | bc`" == "1" ] || [ "`echo "$qlength >= $warn_2" | bc`" == "1" ] ); then 250 | STATE="WARNING" 251 | status=1 252 | fi 253 | fi 254 | if [ "$critical" -ne "99999" ]; then 255 | if ( [ "`echo "$qsize >= $crit_1" | bc`" == "1" ] || [ "`echo "$qlength >= $crit_2" | bc`" == "1" ] ); then 256 | STATE="CRITICAL" 257 | status=2 258 | fi 259 | fi 260 | 261 | 262 | # Printing the results: 263 | MSG="$STATE - Disk Queue Stats: Average Request Size=$qsize Average Queue Length=$qlength" 264 | PERFDATA=" | qsize=$qsize; queue_length=$qlength;" 265 | fi 266 | 267 | #------------Queue Test End------------- 268 | 269 | #------------Wait Time Test------------- 270 | 271 | #Parse values. Warning - svc time will soon be deprecated and these will need to be changed. Future parser could look at first line (labels) to suggest correct column to return 272 | if [ "$waittime" == "1" ]; then 273 | avgwait=`echo "$TMPX" | awk '{print $10}'` 274 | avgrwait=`echo "$TMPX" | awk '{print $11}'` 275 | avgwwait=`echo "$TMPX" | awk '{print $12}'` 276 | avgsvctime=`echo "$TMPX" | awk '{print $13}'` 277 | avgcpuutil=`echo "$TMPX" | awk '{print $14}'` 278 | 279 | # "Converting" values to float (string replace , with .) 280 | avgwait=${avgwait/,/.} 281 | avgrwait=${avgrwait/,/.} 282 | avgwwait=${avgwwait/,/.} 283 | avgsvctime=${avgsvctime/,/.} 284 | avgcpuutil=${avgcpuutil/,/.} 285 | 286 | # Comparing the result and setting the correct level: 287 | if [ "$warning" -ne "99999" ]; then 288 | if ( [ "`echo "$avgwait >= $warn_1" | bc`" == "1" ] || [ "`echo "$avgrwait >= $warn_2" | bc -q`" == "1" ] || \ 289 | [ "`echo "$avgwwait >= $warn_3" | bc`" == "1" ] || [ "`echo "$avgsvctime >= $warn_4" | bc -q`" == "1" ] || \ 290 | [ "`echo "$avgcpuutil >= $warn_5" | bc`" == "1" ] ); then 291 | STATE="WARNING" 292 | status=1 293 | fi 294 | fi 295 | if [ "$critical" -ne "99999" ]; then 296 | if ( [ "`echo "$avgwait >= $crit_1" | bc`" == "1" ] || [ "`echo "$avgrwait >= $crit_2" | bc -q`" == "1" ] || \ 297 | [ "`echo "$avgwwait >= $crit_3" | bc`" == "1" ] || [ "`echo "$avgsvctime >= $crit_4" | bc -q`" == "1" ] || \ 298 | [ "`echo "$avgcpuutil >= $crit_5" | bc`" == "1" ] ); then 299 | STATE="CRITICAL" 300 | status=2 301 | fi 302 | fi 303 | 304 | # Printing the results: 305 | MSG="$STATE - Wait Time Stats: Avg I/O Wait Time (ms)=$avgwait Avg Read Wait Time (ms)=$avgrwait Avg Write Wait Time (ms)=$avgwwait Avg Service Wait Time (ms)=$avgsvctime Avg CPU Utilization=$avgcpuutil" 306 | PERFDATA=" | avg_io_waittime_ms=$avgwait; avg_r_waittime_ms=$avgrwait; avg_w_waittime_ms=$avgwwait; avg_service_waittime_ms=$avgsvctime; avg_cpu_utilization=$avgcpuutil;" 307 | fi 308 | 309 | #------------Wait Time End------------- 310 | 311 | # now output the official result 312 | echo -n "$MSG" 313 | if [ "x$printperfdata" == "x1" ]; then echo -n "$PERFDATA"; fi 314 | echo "" 315 | exit $status 316 | #----------/check_iostat.sh----------- -------------------------------------------------------------------------------- /check_mem.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #nagios exit code 4 | STATE_OK=0 5 | STATE_WARNING=1 6 | STATE_CRITICAL=2 7 | STATE_UNKNOWN=3 8 | 9 | help () { 10 | local command=`basename $0` 11 | echo "NAME 12 | ${command} -- check memory status 13 | SYNOPSIS 14 | ${command} [OPTION] 15 | DESCRIPTION 16 | -w warning= 17 | -c critical= 18 | USAGE: 19 | $0 -w 50% -c 60%" 1>&2 20 | exit ${STATE_WARNING} 21 | } 22 | 23 | check_num () { 24 | local num_str="$1" 25 | echo ${num_str}|grep -E '^[0-9]+$' >/dev/null 2>&1 || local stat='not a positive integers!' 26 | if [ "${stat}" = 'not a positive integers!' ];then 27 | echo "${num_str} ${stat}" 1>&2 28 | exit ${STATE_WARNING} 29 | else 30 | local num_int=`echo ${num_str}*1|bc` 31 | if [ ${num_int} -lt 0 ];then 32 | echo "${num_int} must be greater than 0!" 1>&2 33 | exit ${STATE_WARNING} 34 | fi 35 | fi 36 | } 37 | 38 | #input 39 | while getopts w:c: opt 40 | do 41 | case "$opt" in 42 | w) 43 | warning=$OPTARG 44 | warning_num=`echo "${warning}"|sed 's/%//g'` 45 | check_num "${warning_num}" 46 | ;; 47 | c) 48 | critical=$OPTARG 49 | critical_num=`echo "${critical}"|sed 's/%//g'` 50 | check_num "${critical_num}" 51 | ;; 52 | *) help;; 53 | esac 54 | done 55 | shift $[ $OPTIND - 1 ] 56 | 57 | [ $# -gt 0 -o -z "${warning_num}" -o -z "${critical_num}" ] && help 58 | 59 | if [ -n "${warning_num}" -a -n "${critical_num}" ];then 60 | if [ ${warning_num} -ge ${critical_num} ];then 61 | echo "-w ${warning} must lower than -c ${critical}!" 1>&2 62 | exit ${STATE_UNKNOWN} 63 | fi 64 | fi 65 | 66 | datas=`awk -F':|k' '$2~/[0-9]+/{datas[$1]=$2}END{for (data in datas) {print data"="datas[data]}}' /proc/meminfo | grep -Ev '[)|(]'` 67 | 68 | var=`echo "${datas}"|sed 's/ //g'` 69 | eval "${var}" 70 | 71 | MemUsed=`echo ${MemTotal}-${MemFree}-${Cached}-${Buffers}|bc` 72 | MemUsage=`echo "${MemUsed}/${MemTotal}*100"|bc -l` 73 | MemUsage_num=`echo ${MemUsage}/1|bc` 74 | #echo ${MemUsage_num} 75 | MemTotal_MB=`echo ${MemTotal}/1024|bc` 76 | MemUsed_MB=`echo ${MemUsed}/1024|bc` 77 | MemFree_MB=`echo ${MemFree}/1024|bc` 78 | Cached_MB=`echo ${Cached}/1024|bc` 79 | Buffers_MB=`echo ${Buffers}/1024|bc` 80 | 81 | message () { 82 | local stat="$1" 83 | echo "MEMORY is ${stat} - Usage: ${MemUsage_num}%. Total: ${MemTotal_MB} MB Used: ${MemUsed_MB} MB Free: ${MemFree_MB} MB | Used=${MemUsed_MB};; Cached=${Cached_MB};; Buffers=${Buffers_MB};; Free=${MemFree_MB};;" 84 | } 85 | 86 | [ ${MemUsage_num} -lt ${warning_num} ] && message "OK" && exit ${STATE_OK} 87 | [ ${MemUsage_num} -ge ${critical_num} ] && message "Critical" && exit ${STATE_CRITICAL} 88 | [ ${MemUsage_num} -ge ${warning_num} ] && message "Warning" && exit ${STATE_WARNING} 89 | -------------------------------------------------------------------------------- /check_nbhao.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin 4 | 5 | left=`ps -ef|grep 'python /home/py27/nbhao/nbhao.py'|grep -v grep|wc -l` 6 | if [ $left -eq 0 ];then 7 | echo "CRITICAL - nbhao server is not running." 8 | exit 2 9 | fi 10 | 11 | declare -i lt 12 | declare -i nt 13 | declare -i interval 14 | 15 | log_time=`tail -n 1 /var/log/nbhao.log|awk '{print $1,$2}'` 16 | lt=`date +%s -d "$log_time"` 17 | nt=`date +%s` 18 | 19 | interval=nt-lt 20 | 21 | if [ $interval -gt 3600 ];then 22 | echo "WARNING - nbhao server's log status is changed an hour ago." 23 | exit 1 24 | else 25 | echo "OK - nbhao server is ok." 26 | exit 0 27 | fi -------------------------------------------------------------------------------- /check_net_traffic.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #set nagios status 4 | STATE_OK=0 5 | STATE_WARNING=1 6 | STATE_CRITICAL=2 7 | STATE_UNKNOWN=3 8 | 9 | usage (){ 10 | echo -en "Usage: $0 -d [ eth|bond ]\nFor example:\t$0 -d bond0 -w 100[B|K|M|G] -c 200[B|K|M|G]\n" 1>&2 11 | exit ${STATE_WARNING} 12 | } 13 | 14 | check_input () { 15 | local str="$1" 16 | echo "${str}"|grep -E '[0-9]+[b|B|k|K|m|M|g|G]$' >/dev/null 2>&1 ||\ 17 | eval "echo ${str} is wrong!;usage" 18 | } 19 | 20 | replace_str () { 21 | local str="$1" 22 | output=`echo "${str}"|sed -r 's/[k|K]/*1024/;s/[m|M]/*1024*1024/;s/[g|G]/*1024*1024*1024/'` 23 | echo ${output} 24 | } 25 | 26 | while getopts w:c:d: opt 27 | do 28 | case "$opt" in 29 | w) 30 | check_input "$OPTARG" 31 | warning_str=`replace_str "$OPTARG"` 32 | warning=`echo "${warning_str}"|bc` 33 | ;; 34 | c) 35 | check_input "$OPTARG" 36 | critical_str=`replace_str "$OPTARG"` 37 | critical=`echo "${critical_str}"|bc` 38 | ;; 39 | d) 40 | dev_id="$OPTARG" 41 | ;; 42 | *) 43 | usage 44 | ;; 45 | esac 46 | done 47 | 48 | shift $[ $OPTIND - 1 ] 49 | 50 | if [ -z "${dev_id}" -o -z "${warning}" -o -z "${critical}" ];then 51 | usage 52 | fi 53 | 54 | source_file='/proc/net/dev' 55 | if [ ! -f "${source_file}" ];then 56 | echo "${source_file} not exsit!" 1>&2 57 | exit ${STATE_WARNING} 58 | fi 59 | 60 | grep "${dev_id}" ${source_file} >/dev/null 2>&1 || dev_stat='not found' 61 | if [ "${dev_stat}" = 'not found' ];then 62 | echo "${dev_id} ${dev_stat}!" 1>&2 63 | usage 64 | fi 65 | 66 | time_now=`date -d now +"%F %T"` 67 | nagios_path='/usr/local/nagios/libexec' 68 | test -d ${nagios_path} || mkdir -p ${nagios_path} && mark="${nagios_path}/net_traffic.${dev_id}" 69 | search_dev=`awk -F':' '/'${dev_id}'/{print $2}' /proc/net/dev|sed -r 's/^[ ]+//'` 70 | info=`echo "${search_dev}"|awk -v date="${time_now}" 'BEGIN{OFS=";"}{print "TIME=\""date"\"","RX="$1,"TX="$9,"DEV='${dev_id}'"}'` 71 | 72 | #debug 73 | #eval "${info}" 74 | #echo $info 75 | #echo $TIME $RX $TX && exit 76 | 77 | marking () { 78 | echo "$info" > ${mark} || exit ${STATE_WARNING} 79 | chown nagios.nagios ${mark} 80 | } 81 | 82 | if [ ! -f "${mark}" ];then 83 | marking 84 | echo "This script is First run! ${info}" 85 | exit ${STATE_OK} 86 | else 87 | old_info=`cat ${mark}` 88 | eval "${old_info}" 89 | OLD_TIME="${TIME}";OLD_RX=${RX};OLD_TX=${TX} 90 | if [ -z "${OLD_RX}" -o -z "${OLD_TX}" ];then 91 | echo "Data Error: ${old_info}" 1>&2 92 | marking 93 | exit ${STATE_WARNING} 94 | fi 95 | fi 96 | 97 | if [ -n "${info}" ];then 98 | eval ${info} 99 | sec_now=`date -d "${TIME}" +"%s"` 100 | sec_old=`date -d "${OLD_TIME}" +"%s"` 101 | sec=`echo "${sec_now}-${sec_old}"|bc|sed 's/-//'` 102 | rx=`echo "(${RX}-${OLD_RX})/${sec}"|bc|sed 's/-//'` 103 | tx=`echo "(${TX}-${OLD_TX})/${sec}"|bc|sed 's/-//'` 104 | marking 105 | #debug 106 | # echo $sec $rx $tx 107 | else 108 | echo "Can not read ${source_file}" 1>&2 109 | exit ${STATE_WARNING} 110 | fi 111 | 112 | human_read () { 113 | local number="$1" 114 | if [ `echo "(${number}-1073741824) > 0"|bc` -eq 1 ];then 115 | output="`echo "scale=2;${number}/1024/1024/1024"|bc` GB/s" 116 | elif [ `echo "(${number}-1048576) > 0"|bc` -eq 1 ];then 117 | output="`echo "scale=2;${number}/1024/1024"|bc` MB/s" 118 | elif [ `echo "(${number}-1024) > 0"|bc` -eq 1 ];then 119 | output="`echo "scale=2;${number}/1024"|bc` KB/s" 120 | else 121 | output="${number} B/s" 122 | fi 123 | echo "${output}" 124 | } 125 | 126 | rx_human_read=`human_read "${rx}"` 127 | tx_human_read=`human_read "${tx}"` 128 | 129 | message () { 130 | local stat="$1" 131 | echo "${DEV} Traffic is ${stat} - In: ${rx_human_read} Out: ${tx_human_read} interval: ${sec}s |in=${rx};${warning};${critical};${min};${max} out=${tx};${warning};${critical};${min};${max}" 132 | } 133 | 134 | #pnp4nagios setting 135 | min=0 136 | max=1073741824 137 | 138 | total_int=`echo "${rx}+${tx}"|bc` 139 | 140 | [ `echo "(${total_int}-${warning}) < 0"|bc` -eq 1 ] && message "OK" && exit ${STATE_OK} 141 | [ `echo "(${total_int}-${critical}) >= 0"|bc` -eq 1 ] && message "Critical" && exit ${STATE_CRITICAL} 142 | [ `echo "(${total_int}-${warning}) >= 0"|bc` -eq 1 ] && message "Warning" && exit ${STATE_WARNING} 143 | 144 | -------------------------------------------------------------------------------- /check_nfs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #系统当前时间 4 | t1=`date "+%Y-%m-%d %H:%M:%S"` 5 | t2=`date +%s -d "$t1"` 6 | 7 | #define status 8 | STATE_OK=0 9 | STATE_WARNING=1 10 | STATE_CRITICAL=2 11 | 12 | cnt=`ps -ef|grep nfs |grep -v grep |wc -l` 13 | if [ $cnt -eq 0 ];then 14 | echo "CRITICAL - NFS service is not running!" 15 | exit $STATE_CRITICAL 16 | else 17 | echo "OK - NFS service is ok!" 18 | exit $STATE_OK 19 | fi 20 | -------------------------------------------------------------------------------- /check_nowsms.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | import urllib2 5 | from xml.dom.minidom import parse 6 | import sys 7 | import argparse 8 | 9 | parser=argparse.ArgumentParser(description="check nowsms status script.") 10 | parser.add_argument("-H",dest="host",help="Host name argument for servers using host headers") 11 | parser.add_argument("-P",dest="port",default=8800,help="nowsms http port ,default 8800.") 12 | parser.add_argument("-u",dest="username",help="nowsms admin username") 13 | parser.add_argument("-p",dest="password",help="nowsms admin user's password") 14 | 15 | args=parser.parse_args() 16 | 17 | if not args.host or not args.port or not args.username or not args.password : 18 | print "Critical - Invalid command,please check." 19 | sys.exit(2) 20 | 21 | url='http://%s:%s/admin/xmlstatus?username=%s&password=%s' % (args.host,args.port,args.username,args.password) 22 | req=urllib2.Request(url) 23 | req.add_header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36") 24 | 25 | try: 26 | response=urllib2.urlopen(req,timeout=5) 27 | DOMTree = parse(response) 28 | except: 29 | print "Critical - nowsms admin status get error." 30 | sys.exit(2) 31 | 32 | nowsms = DOMTree.documentElement 33 | 34 | smsc = nowsms.getElementsByTagName("SMSCStatus") 35 | mmsc = nowsms.getElementsByTagName("MMSCRouteStatus") 36 | sms_sent = nowsms.getElementsByTagName("SMSSent") 37 | sms_received = nowsms.getElementsByTagName("SMSReceived") 38 | 39 | status = smsc[0].getElementsByTagName('Status')[0].childNodes[0].data 40 | mlast7days = mmsc[0].getElementsByTagName('MessagesLast7Days')[0].childNodes[0].data 41 | 42 | sms_sent_last7days = sms_sent[0].getElementsByTagName('MessagesLast7Days')[0].childNodes[0].data 43 | sms_received_last7days = sms_received[0].getElementsByTagName('MessagesLast7Days')[0].childNodes[0].data 44 | 45 | if status != 'OK': 46 | detail=smsc[0].getElementsByTagName('StatusDetail')[0].childNodes[0].data 47 | print "%s - %s" % (status,detail) 48 | sys.exit(2) 49 | else: 50 | print "%s - nowsms is ok. | SMSSent7DAYS=%s;;;;SMSReceived7DAYS=%s;;;;" % (status,sms_sent_last7days,sms_received_last7days) 51 | sys.exit(0) 52 | -------------------------------------------------------------------------------- /check_pgbouncer.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #define status 4 | STATE_OK=0 5 | STATE_WARNING=1 6 | STATE_CRITICAL=2 7 | 8 | res=`/opt/PostgreSQL/9.2/bin/psql -U postgres -p 5432 -d pgbouncer -A -t -c "show pools"` 9 | conns=0 10 | cl_waitings=0 11 | cl_actives=0 12 | req=0 13 | pg_in=0 14 | pg_out=0 15 | 16 | for line in $res 17 | do 18 | conn=`echo $line |awk -F '|' '{print $3}' ` 19 | cl_waiting=`echo $line |awk -F '|' '{print $4}' ` 20 | let conns=$conn+$conns 21 | let cl_waitings=$cl_waiting+$cl_waitings 22 | let cl_actives=$conn+$cl_actives 23 | done 24 | 25 | let conns=$conns+$cl_waitings 26 | 27 | max_conn=`grep "max_client_conn" /etc/pgbouncer/pgbouncer.ini |awk '{print $NF}'` 28 | 29 | w_conn=`echo "$max_conn*0.8"|bc` 30 | c_conn=`echo "$max_conn*0.95"|bc` 31 | w_conn=`echo ${w_conn%.*}` 32 | c_conn=`echo ${c_conn%.*}` 33 | 34 | left=`tail /var/log/pgbouncer/pgbouncer.log |grep -c "LOG Stats:.*req/s"` 35 | if [ $left -ne 0 ];then 36 | req=`tail /var/log/pgbouncer/pgbouncer.log |grep "LOG Stats:.*req/s" |tail -n 1 |awk '{print $6}'` 37 | pg_in=`tail /var/log/pgbouncer/pgbouncer.log |grep "LOG Stats:.*req/s" |tail -n 1 |awk '{print $9}'` 38 | pg_out=`tail /var/log/pgbouncer/pgbouncer.log |grep "LOG Stats:.*req/s" |tail -n 1 |awk '{print $12}'` 39 | pg_in=`echo "$pg_in/1024"|bc` 40 | pg_out=`echo "$pg_out/1024"|bc` 41 | fi 42 | 43 | if [ $conns -gt $w_conn -o $req -lt 600 ];then 44 | echo "WARNING - max_conn=$max_conn,conns=$conns,req=$req,cl_waiting=$cl_waitings,cl_active=$cl_actives,in=$pg_in,out=$pg_out | conn=$conns;$w_conn;$c_conn;;req=$req;600;300;;" 45 | exit $STATE_WARNING 46 | fi 47 | 48 | if [ $conns -gt $c_conn -o $req -lt 300 ];then 49 | echo "CRITICAL - max_conn=$max_conn,conns=$conns,req=$req,cl_waiting=$cl_waitings,cl_active=$cl_actives,in=$pg_in,out=$pg_out | conn=$conns;$w_conn;$c_conn;;req=$req;600;300;;" 50 | exit $STATE_CRITICAL 51 | fi 52 | 53 | 54 | a=`tail /var/log/pgbouncer/pgbouncer.log |grep -c "LOG Stats"` 55 | 56 | if [ $a -lt 1 ];then 57 | echo "WARNING - Please check pgbouncer stats!" 58 | exit $STATE_WARNING 59 | fi 60 | 61 | echo "OK - It's ok! max_conn=$max_conn,conns=$conns,req=$req,cl_waiting=$cl_waitings,cl_active=$cl_actives,in=$pg_in,out=$pg_out | conn=$conns;$w_conn;$c_conn;;req=$req;600;300;;" 62 | exit $STATE_OK -------------------------------------------------------------------------------- /check_pglag.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #define status 4 | STATE_OK=0 5 | STATE_WARNING=1 6 | STATE_CRITICAL=2 7 | 8 | lag_w=3600 9 | lag_c=10800 10 | 11 | #lag time second 12 | lag_tm=`/opt/PostgreSQL/93/bin/psql -U postgres -p 5432 -d postgres -A -t -c "SELECT CASE WHEN pg_last_xlog_receive_location() = pg_last_xlog_replay_location() THEN 0 ELSE EXTRACT (EPOCH FROM now() - pg_last_xact_replay_timestamp())::integer END AS replication_lag;"` 13 | 14 | if [ $? -ne 0 ];then 15 | echo "CRITICAL - PostgreSQL is not running." 16 | exit $STATE_CRITICAL 17 | fi 18 | 19 | if [ $lag_tm -gt $lag_w ];then 20 | echo "WARNING - Lag time $lag_tm s. | lag_tm=$lag_tm;$lag_w;$lag_c;;" 21 | exit $STATE_WARNING 22 | fi 23 | 24 | if [ $lag_tm -gt $lag_c ];then 25 | echo "CRITICAL - Lag time $lag_tm s. | lag_tm=$lag_tm;$lag_w;$lag_c;;" 26 | exit $STATE_CRITICAL 27 | fi 28 | 29 | echo "OK - Lag time $lag_tm s. | lag_tm=$lag_tm;$lag_w;$lag_c;;" 30 | exit $STATE_OK 31 | -------------------------------------------------------------------------------- /check_postgresql.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin 4 | 5 | #process 6 | left=`ps -ef|grep '/opt/PostgreSQL/93/bin/postgres'|grep -cv grep` 7 | if [ $left -eq 0 ];then 8 | echo "Critical - PostgreSQL is not running." 9 | exit 2 10 | fi 11 | 12 | #idle in transaction 13 | left=`ps -ef|grep postgres|grep 'idle in transaction'|grep -cv grep` 14 | if [ $left -gt 5 ];then 15 | echo "Warning - PostgreSQL idle in transaction count is $left." 16 | exit 1 17 | fi 18 | 19 | #connections 20 | max=1000 21 | conns=`ps -ef|grep postgres|grep -cv grep` 22 | 23 | let conn_ratio=($conns*100)/$max 24 | if [ $conn_ratio -gt 95 ];then 25 | echo "Critical - PostgreSQL connections ratio reached ${conn_ratio}%." 26 | exit 2 27 | fi 28 | if [ $conn_ratio -gt 80 ];then 29 | echo "Warning - PostgreSQL connections ratio reached ${conn_ratio}%." 30 | exit 1 31 | fi 32 | 33 | #slow query 34 | sql="select count(pid) from pg_stat_activity where state != 'idle' and query not ilike '%pg_stat_activity%' and now() - query_start > '10 minutes'::interval;" 35 | slow_query_cnt=`/opt/PostgreSQL/93/bin/psql -h 127.0.0.1 -p 5432 -U postgres -d postgres -c "$sql" -t -A` 36 | if [ $slow_query_cnt -ne 0 ];then 37 | echo "Warning - PostgreSQL slow query count is $slow_query_cnt. | conn_ratio=$conn_ratio;80;95;;slow_query=$slow_query_cnt;;;;" 38 | echo 1 39 | fi 40 | 41 | #ok 42 | echo "OK - PostgreSQL is running ok. | conn_ratio=$conn_ratio;80;95;;slow_query=$slow_query_cnt;;;;" 43 | exit 0 -------------------------------------------------------------------------------- /check_pptp.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #系统当前时间 4 | t1=`date "+%Y-%m-%d %H:%M:%S"` 5 | t2=`date +%s -d "$t1"` 6 | 7 | #define status 8 | STATE_OK=0 9 | STATE_WARNING=1 10 | STATE_CRITICAL=2 11 | 12 | cnt=`ps -ef|grep pptp |grep -v grep |wc -l` 13 | if [ $cnt -eq 0 ];then 14 | echo "CRITICAL - PPTP service is not running!" 15 | exit $STATE_CRITICAL 16 | else 17 | con=`ps -ef|grep pptpd-options |grep -v grep |wc -l` 18 | if [ $con -gt 5 -a $con -le 10 ];then 19 | echo "WARNING - There are $con vpn users connected! | conn=$con;5;10;;" 20 | exit $STATE_WARNING 21 | elif [ $con -gt 10 ];then 22 | echo "CRITICAL - There are $con vpn users connected! | conn=$con;5;10;;" 23 | exit $STATE_CRITICAL 24 | else 25 | echo "OK - PPTP service is running ok! | conn=$con;5;10;;" 26 | exit $STATE_OK 27 | fi 28 | fi -------------------------------------------------------------------------------- /check_shadowsocks.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin 4 | 5 | left=`ps -ef|grep 'python /root/shadowsocks/shadowsocks/server.py'|grep -v grep|wc -l` 6 | if [ $left -eq 0 ];then 7 | echo "CRITICAL - shadowsocks server is not running." 8 | exit 2 9 | fi 10 | 11 | echo "OK - shadowsocks server is ok." 12 | exit 0 -------------------------------------------------------------------------------- /check_sms.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | #define status 5 | STATE_OK=0 6 | STATE_WARNING=1 7 | STATE_CRITICAL=2 8 | 9 | sms_home=/home/zhangnq/sms 10 | 11 | cd $sms_home 12 | 13 | a=`ps -ef |grep -v grep |grep -c smsserver` 14 | if [ $a -eq 0 ];then 15 | echo "CRITICAL - SMS service is not running!" 16 | exit $STATE_CRITICAL 17 | fi 18 | 19 | s1=`tail -n 10 $sms_home/sms.log |grep -c ERROR` 20 | 21 | #modem status 22 | 23 | m_cnt=0 24 | err=0 25 | for modem in `grep ^[a-z] SmsServer.conf |grep "gateway.*" |cut -d, -f1|awk -F '=' '{print $NF}'` 26 | do 27 | m=`grep "GTW: $modem: Gateway status" sms.log |sed -n '$p'|awk '{print $NF}'` 28 | if [ "$m" != "STARTED" ];then 29 | let err=$err+1 30 | fi 31 | let m_cnt=$m_cnt+1 32 | done 33 | 34 | case $err in 35 | 36 | $m_cnt) 37 | echo "CRITICAL - All gateway's status is error!" 38 | exit $STATE_CRITICAL 39 | ;; 40 | 1 | 2 | 3 | 4) 41 | echo "WARNING - There are $err modems running error!" 42 | ;; 43 | *) 44 | if [ $s1 -ne 0 ];then 45 | echo "CRITICAL - SMS service is running error!" 46 | exit $STATE_CRITICAL 47 | else 48 | echo "OK - SMS service is Ok!" 49 | exit $STATE_OK 50 | fi 51 | ;; 52 | esac -------------------------------------------------------------------------------- /check_speed.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ################################## 4 | # 5 | ####nagios监控脚本 6 | ####作者:章郎虫 7 | ####博客:http://www.sijitao.net/ 8 | # 9 | ################################## 10 | 11 | PROGNAME=`basename $0` 12 | VERSION="Version 1.0" 13 | AUTHOR="2013.12.03,www.sijitao.net" 14 | 15 | ST_OK=0 16 | ST_WR=1 17 | ST_CR=2 18 | ST_UK=3 19 | 20 | interval=5 21 | url="http://mirrors.163.com/centos/5.5/isos/x86_64/CentOS-5.5-x86_64-LiveCD.iso" 22 | 23 | print_version() { 24 | echo "$VERSION $AUTHOR" 25 | } 26 | 27 | print_help() { 28 | print_version $PROGNAME $VERSION 29 | echo "$PROGNAME is a Nagios plugin to monitor download speed" 30 | echo "Use of wget download url file" 31 | echo "When using optional warning/critical thresholds all values except" 32 | echo "Usage parameters:" 33 | echo "" 34 | echo "$PROGNAME [-i/--interval] [-u|--url] [-w/--warning] [-c/--critical]" 35 | echo "" 36 | echo "Options:" 37 | echo " --interval|-i)" 38 | echo " Defines the download file times" 39 | echo " propose set < 5 second and > 10 second" 40 | echo " Default is: 5 second" 41 | echo "" 42 | echo " --url|-u)" 43 | echo " Sets url page" 44 | echo " Defautl is :http://mirrors.163.com/centos/5.5/isos/x86_64/CentOS-5.5-x86_64-LiveCD.iso" 45 | echo " Please set Fastest url" 46 | echo "" 47 | echo " --warning|-w)" 48 | echo " Sets a warning level for download speed. Defautl is: off" 49 | echo "" 50 | echo " --critical|-c)" 51 | echo " Sets a critical level for download speed. Defautl is: off" 52 | exit $ST_UK 53 | } 54 | 55 | while test -n "$1";do 56 | case "$1" in 57 | --help|-h) 58 | print_help 59 | exit $ST_UK 60 | ;; 61 | --url|-u) 62 | url=$2 63 | shift 64 | ;; 65 | --interval|-i) 66 | interval=$2 67 | shift 68 | ;; 69 | --warning|-w) 70 | warn=$2 71 | shift 72 | ;; 73 | --critical|-c) 74 | crit=$2 75 | shift 76 | ;; 77 | *) 78 | echo "Unknown argument: $1" 79 | print_help 80 | exit $ST_UK 81 | ;; 82 | esac 83 | shift 84 | done 85 | 86 | val_wcdiff() { 87 | if [ ${warn} -lt ${crit} ] 88 | then 89 | wcdiff=1 90 | fi 91 | } 92 | 93 | get_speed() { 94 | wget -b $url > /dev/null 95 | sleep $interval 96 | BS="`cat wget-log |tail -n20 |awk '{print $8}'|sed 's/K//'|awk '{sum+=$1};END{print sum}'`" 97 | speed=`echo $BS / 19|bc` 98 | killall wget 99 | rm CentOS* 100 | rm wget-log 101 | } 102 | do_output() { 103 | output="speed:${speed}" 104 | } 105 | do_perfdata() { 106 | perfdata="'speed'=${speed}" 107 | } 108 | 109 | if [ -n "$warn" -a -n "$crit" ] 110 | then 111 | val_wcdiff 112 | if [ "$wcdiff" = 1 ];then 113 | echo "Please adjust your warning/critical thresholds. The critical must be lower than the warning level!" 114 | exit $ST_UK 115 | fi 116 | fi 117 | 118 | get_speed 119 | do_output 120 | do_perfdata 121 | 122 | if [ -n "$warn" -a -n "$crit" ];then 123 | if [ $speed -le $warn -a $speed -gt $crit ];then 124 | echo "WARNING - $output |$perfdata" 125 | exit $ST_WR 126 | elif [ $speed -lt $crit ];then 127 | echo "CRITICAL - $output|$perfdata" 128 | exit $ST_CR 129 | else 130 | echo "OK - $output|$perfdata" 131 | exit $ST_OK 132 | fi 133 | else 134 | echo "OK - $output|$perfdata" 135 | exit $ST_OK 136 | fi 137 | -------------------------------------------------------------------------------- /check_tcp_stat.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #nagios exit code 4 | STATE_OK=0 5 | STATE_WARNING=1 6 | STATE_CRITICAL=2 7 | STATE_UNKNOWN=3 8 | 9 | #help 10 | help () { 11 | local command=`basename $0` 12 | echo "NAME 13 | ${command} -- check network status 14 | SYNOPSIS 15 | ${command} [OPTION] 16 | DESCRIPTION 17 | -H IP ADDRESS 18 | -p LOCAL PORT 19 | -S [TIME_WAIT|FIN_WAIT|ESTABLISHED|CLOSING|SYN_SEND|TIMED_WAIT|LISTEN] 20 | -w warning 21 | -c critical 22 | USAGE: 23 | Total connections: 24 | $0 -w 100 -c 200 25 | Port: 26 | $0 -p 8819 -w 100 -c 200 27 | Host and Port: 28 | $0 -H 192.168.0.6 -p 8819 -w 100 -c 200 29 | Status: 30 | $0 -H 192.168.0.6 -p 8819 -S ESTABLISHED -w 100 -c 200" 1>&2 31 | exit ${STATE_WARNING} 32 | } 33 | 34 | check_num () { 35 | local num_str="$1" 36 | echo ${num_str}|grep -E '^[0-9]+$' >/dev/null 2>&1 || local stat='not a positive integers!' 37 | if [ "${stat}" = 'not a positive integers!' ];then 38 | echo "${num_str} ${stat}" 1>&2 39 | exit ${STATE_WARNING} 40 | else 41 | local num_int=`echo ${num_str}*1|bc` 42 | if [ ${num_int} -lt 0 ];then 43 | echo "${num_int} must be greater than 0!" 1>&2 44 | exit ${STATE_WARNING} 45 | fi 46 | fi 47 | } 48 | 49 | check_ip () { 50 | local ip_str="$1" 51 | echo "${ip_str}"|grep -P '^\d{1,3}(\.\d{1,3}){3}$' >/dev/null 2>&1 || local stat='not a ip!' 52 | if [ "${ip_stat}" = 'not a ip!' ];then 53 | echo "${ip_str} ${stat}" 1>&2 54 | exit ${STATE_WARNING} 55 | fi 56 | } 57 | 58 | check_state () { 59 | local stat_str="$1" 60 | if [ -n "${stat_str}" ];then 61 | case "${stat_str}" in 62 | TIME_WAIT|FIN_WAIT|ESTABLISHED|CLOSING|SYN_SEND|TIMED_WAIT) 63 | cmd="netstat -nt|grep ${stat_str}" 64 | ;; 65 | LISTEN) 66 | cmd="netstat -ntl" 67 | ;; 68 | *) 69 | echo "This script only support [TIME_WAIT|FIN_WAIT|ESTABLISHED|CLOSING|SYN_SEND|TIMED_WAIT]" 1>&2 70 | exit ${STATE_WARNING} 71 | ;; 72 | esac 73 | fi 74 | } 75 | 76 | logging () { 77 | local now_date=`date -d now +"%F %T"` 78 | local log_path='/var/log/tcp' 79 | local log_name=`date -d "now" +"%F"` 80 | 81 | local uid=`id -u` 82 | if [ "${uid}" == '0' ];then 83 | test -d ${log_path} || mkdir -p ${log_path}/ 84 | chown nagios.nagios -R ${log_path} 85 | fi 86 | 87 | log="${log_path}/tcp_stat_${log_name}.log" 88 | echo "${now_date} ${info}"|sed 's/;//g' >> ${log} 89 | test -f ${log} && chown nagios.nagios ${log} 90 | } 91 | 92 | message () { 93 | local stat="$1" 94 | echo "TCP status is ${stat} - ${info}|Total=${total_connections_int};${warning};${critical};${min};${max};TIME_WAIT=${timewait_connections_int};;CLOSE_WAIT=${closewait_connections_int};;ESTABLISHED=${established_connections_int};;SYN_RECV=${synrecv_connections_int};;LAST_ACK=${lastack_connections_int};;" 95 | } 96 | 97 | #input 98 | while getopts w:c:p:H:S:l opt 99 | do 100 | case "$opt" in 101 | w) 102 | warning=$OPTARG 103 | check_num "${warning}" 104 | ;; 105 | c) 106 | critical=$OPTARG 107 | check_num "${critical}" 108 | ;; 109 | p) 110 | port="$OPTARG" 111 | check_num "${port}" 112 | ;; 113 | H) 114 | ip="$OPTARG" 115 | check_ip "${ip}" 116 | ;; 117 | S) 118 | state="$OPTARG" 119 | check_state "${state}" 120 | ;; 121 | l) 122 | log_status='on' 123 | ;; 124 | *) help;; 125 | esac 126 | done 127 | shift $[ $OPTIND - 1 ] 128 | 129 | #[ $# -gt 0 -o -z "${warning}" -o -z "${critical}" ] && help 130 | [ $# -gt 0 -o -z "${warning}" ] && help 131 | 132 | if [ -n "${warning}" -a -n "${critical}" ];then 133 | if [ ${warning} -ge ${critical} ];then 134 | echo "-w ${warning} must lower than -c ${critical}!" 1>&2 135 | exit ${STATE_UNKNOWN} 136 | fi 137 | fi 138 | 139 | if [ -n "${warning}" -a -z "${critical}" ];then 140 | if [ "${warning}" == "0" ];then 141 | critical="${warning}" 142 | else 143 | echo "Critical can not be empty!" 1>&2 144 | exit ${STATE_UNKNOWN} 145 | fi 146 | fi 147 | 148 | [ -z "${state}" ] && netstat_cmd="netstat -nt" || netstat_cmd="${cmd}" 149 | [ -z "${ip}" -a -z "${port}" ] && run_cmd="${netstat_cmd}" 150 | [ -n "${ip}" -a -z "${port}" ] && run_cmd="${netstat_cmd}|grep \"${ip}:\"" 151 | [ -n "${port}" -a -z "${ip}" ] && run_cmd="${netstat_cmd}|grep -P \":${port}\s\"" 152 | [ -n "${port}" -a -n "${ip}" ] && run_cmd="${netstat_cmd}|grep -P \"${ip}:${port}\s\"" 153 | 154 | info=`eval "${run_cmd}"|\ 155 | awk 'BEGIN{OFS=":";ORS="; "}/^tcp/{stats[$(NF)]+=1;sum++}END{print "Total",sum;for (stat in stats) {print stat,stats[stat]}}'` 156 | 157 | echo "${info}"|grep -E '[0-9]' >/dev/null 2>&1 || info="Total:0" 158 | 159 | min=0 160 | max=4096 161 | total_connections_str=`echo "${info}"|grep -oP "Total:\d+"|awk -F':' '{print $2}'` 162 | total_connections_int=`echo "${total_connections_str}*1"|bc` 163 | echo "${total_connections_int}"|grep -E '^[0-9]+$' >/dev/null 2>&1 ||\ 164 | eval "echo ${total_connections_int} not a number!;exit ${STATE_UNKNOWN}" 165 | 166 | #统计tcp不同连接状态数量 167 | stat_count(){ 168 | local stat_str=$1 169 | str=`echo "${info}"|grep -oP "$stat_str:\d+"|awk -F':' '{print $2}'` 170 | if [ ! $str ];then 171 | str="0" 172 | fi 173 | int=`echo "${str}*1"|bc` 174 | echo $int 175 | } 176 | timewait_connections_int=`stat_count "TIME_WAIT"` 177 | closewait_connections_int=`stat_count "CLOSE_WAIT"` 178 | established_connections_int=`stat_count "ESTABLISHED"` 179 | synrecv_connections_int=`stat_count "SYN_RECV"` 180 | lastack_connections_int=`stat_count "LAST_ACK"` 181 | 182 | [ "${log_status}" == 'on' ] && logging 183 | 184 | if [ "${warning}" == "0" ];then 185 | if [ ${total_connections_int} -eq 0 ];then 186 | message "Warning" 187 | exit ${STATE_WARNING} 188 | else 189 | message "OK" 190 | exit ${STATE_OK} 191 | fi 192 | fi 193 | 194 | [ ${total_connections_int} -lt ${warning} ] && message "OK" && exit ${STATE_OK} 195 | [ ${total_connections_int} -ge ${critical} ] && message "Critical" && exit ${STATE_CRITICAL} 196 | [ ${total_connections_int} -ge ${warning} ] && message "Warning" && exit ${STATE_WARNING} 197 | -------------------------------------------------------------------------------- /check_tomcat_log.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games 4 | export LANG=zh_CN.UTF-8 5 | export LANGUAGE=zh_CN:zh 6 | 7 | name=$1 8 | logpath=$2 9 | 10 | if [ ! $name ];then 11 | echo "Please input name." 12 | exit 2 13 | fi 14 | if [ ! $logpath ];then 15 | echo "Please input log path." 16 | exit 2 17 | fi 18 | 19 | #logs timestamp monitor 20 | left=$(tail -n 100 $logpath|awk '{print $1,$2}'|grep '^[0-9]'|tail -n 1) 21 | t1=$(date -d "$left" "+%s") 22 | if [ $? -ne 0 ];then 23 | left=$(ls -l $logpath |awk '{print $(NF-1)}') 24 | t1=$(date -d "$left" "+%s") 25 | fi 26 | 27 | t2=$(date "+%s") 28 | let interval=$t2-$t1 29 | 30 | if [ $interval -gt 300 ];then 31 | echo "Warning - ${name}'s log haven't output for more than 5 minutes." 32 | exit 1 33 | fi 34 | 35 | #### 36 | echo "OK - ${name}'s log is ok." 37 | exit 0 38 | -------------------------------------------------------------------------------- /check_tp_er5120.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | import urllib 5 | import urllib2 6 | import cookielib 7 | import hashlib 8 | import sys 9 | import re 10 | import argparse 11 | 12 | parser=argparse.ArgumentParser(description="Check TP-ER5120 Traffic.") 13 | parser.add_argument("-H",dest="host",help="Host name argument for servers using host headers") 14 | parser.add_argument("-P",dest="port",default=8080,help="router http port ,default 8080.") 15 | parser.add_argument("-I",dest="interface",default='WAN1',help="router wan interface,default WAN1.") 16 | parser.add_argument("-u",dest="username",help="router admin username") 17 | parser.add_argument("-p",dest="password",help="router admin's password") 18 | parser.add_argument("-W",dest="warning",default=40,help="warning traffic,default 40Mbps.") 19 | parser.add_argument("-C",dest="critical",default=50,help="critical traffic,default 50Mbps.") 20 | 21 | args=parser.parse_args() 22 | if not args.host or not args.port or not args.username or not args.password : 23 | print "Critical - Invalid command,please check." 24 | sys.exit(2) 25 | 26 | #定义需要用到的网址 27 | bandinfo_url='http://%s:%s/userRpm/Monitor_bandinfo.htm' % (args.host,args.port) 28 | index_url='http://%s:%s/logon/logon.htm' % (args.host,args.port) 29 | login_url='http://%s:%s/logon/loginJump.htm' % (args.host,args.port) 30 | logout_url='http://%s:%s/logon/logout.htm' % (args.host,args.port) 31 | loginconfirm_url='http://%s:%s/logon/loginConfirm.htm' % (args.host,args.port) 32 | username=args.username 33 | password=args.password 34 | interface=args.interface 35 | #监控带宽阀值,单位Mbps 36 | try: 37 | trans_warning=int(args.warning) 38 | except: 39 | print "Please input valid warning traffic,must to be a number." 40 | sys.exit(2) 41 | try: 42 | trans_critical=int(args.critical) 43 | except: 44 | print "Please input valid critical traffic,must to be a number." 45 | sys.exit(2) 46 | 47 | 48 | class MyRequest: 49 | def __init__(self): 50 | self.__agent='My Spider/1.0.0 (admin@sijitao.net)' 51 | self.__params = {} 52 | self.__header = { 53 | 'User-Agent':self.__agent, 54 | } 55 | 56 | def add_query_param(self, k, v): 57 | if self.__params is None: 58 | self.__params = {} 59 | self.__params[k] = v 60 | 61 | def set_query_param(self,params={}): 62 | self.__params = params 63 | 64 | def add_header(self, k, v): 65 | if self.__header is None: 66 | self.__header = dict(k=v) 67 | else: 68 | self.__header[k] = v 69 | def get_headers(self): 70 | return self.__header 71 | 72 | def set_user_agent(self, agent): 73 | self.add_header('User-Agent', agent) 74 | 75 | def do_action(self,url,method=''): 76 | data=urllib.urlencode(self.__params) 77 | req=urllib2.Request(url,headers=self.get_headers()) 78 | req.add_data(data) 79 | if method: 80 | req.get_method = lambda: method 81 | try: 82 | response = urllib2.urlopen(req) 83 | return response 84 | except urllib2.URLError as e: 85 | if hasattr(e, 'code'): 86 | #print("Request %s code %s") % (url,e.code) 87 | pass 88 | elif hasattr(e, 'reason'): 89 | #print("Request %s reason %s") % (url,e.reason) 90 | pass 91 | return False 92 | except: 93 | print("Request %s error.") % url 94 | return False 95 | 96 | 97 | #cookie 98 | cj = cookielib.LWPCookieJar() 99 | cookie_support = urllib2.HTTPCookieProcessor(cj) 100 | opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler) 101 | urllib2.install_opener(opener) 102 | 103 | #get cookie 104 | try: 105 | opener.open(index_url) 106 | except: 107 | print "Critical - Get cookie error." 108 | sys.exit(2) 109 | for ck in cj: 110 | cookie = ck.value 111 | 112 | #login 113 | request=MyRequest() 114 | 115 | value_tmp="%s:%s:%s" % (username,password,cookie) 116 | value_encode="%s:%s" % (username,hashlib.md5(value_tmp).hexdigest()) 117 | request.add_query_param('encoded', value_encode) 118 | request.add_query_param('nonce',cookie) 119 | login_response=request.do_action(login_url) 120 | 121 | if login_response: 122 | #不能多人同时登录 123 | login_html=login_response.read().decode('gb2312') 124 | pattern=re.compile('loginConfirm') 125 | result=pattern.findall(login_html) 126 | if result: 127 | request.do_action(loginconfirm_url,method='GET') 128 | 129 | bandinfo_response=request.do_action(bandinfo_url,method='GET') 130 | if bandinfo_response: 131 | bandinfo_html=bandinfo_response.read().decode('gb2312') 132 | pattern=re.compile(r'%s.*,' % interface) 133 | result=pattern.findall(bandinfo_html) 134 | 135 | try: 136 | result=result[0].encode("utf-8") 137 | except: 138 | print "Warning - Username or password error." 139 | sys.exit(1) 140 | trans_in=int(result.split(",")[1].replace('"',''))/1000000.0 141 | trans_out=int(result.split(",")[2].replace('"',''))/1000000.0 142 | trans_total=trans_in+trans_out 143 | if trans_total=trans_warning and trans_total=trans_critical: 152 | print "Critical - Traffic in %.2f Mbps, out %.2f Mbps, total %.2f Mbps.|in=%.2f;;;;out=%.2f;;;;" % (trans_in,trans_out,trans_total,trans_in,trans_out) 153 | opener.open(logout_url) 154 | sys.exit(2) 155 | 156 | else: 157 | print "Critical - Get band info error." 158 | #logout 159 | opener.open(logout_url) 160 | sys.exit(2) 161 | #logout 162 | opener.open(logout_url) 163 | else: 164 | print "Critical - Login error." 165 | sys.exit(2) 166 | 167 | -------------------------------------------------------------------------------- /pnp4nagios/check_mem.php: -------------------------------------------------------------------------------- 1 | 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy 6 | * of this software and associated documentation files (the "Software"), to deal 7 | * in the Software without restriction, including without limitation the rights 8 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | * copies of the Software, and to permit persons to whom the Software is furnished 10 | * to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | * THE SOFTWARE. 22 | * 23 | * This file is part of the nagios-puppet bundle that can be found 24 | * at https://github.com/jasonhancock/nagios-memory 25 | */ 26 | $alpha = 'CC'; 27 | $colors = array( 28 | '#850707' . $alpha, 29 | '#FFDB87' . $alpha, 30 | '#25345C' . $alpha, 31 | '#88008A' . $alpha, 32 | '#4F7774' . $alpha, 33 | ); 34 | $opt[1] = sprintf('-T 55 -l 0 --vertical-label "Bytes" --title "%s / Memory Usage"', $hostname); 35 | $def[1] = ''; 36 | $count = 0; 37 | foreach ($DS as $i) { 38 | $def[1] .= rrd::def("var$i", $rrdfile, $DS[$i], 'AVERAGE'); 39 | if ($i == '1') { 40 | $def[1] .= rrd::area ("var$i", $colors[$count], rrd::cut(ucfirst($NAME[$i]), 15)); 41 | } else { 42 | $def[1] .= rrd::area ("var$i", $colors[$count], rrd::cut(ucfirst($NAME[$i]), 15), 'STACK'); 43 | } 44 | $def[1] .= rrd::gprint ("var$i", array('LAST','MAX','AVERAGE'), "%4.2lf %s\\t"); 45 | $count++; 46 | } 47 | 48 | -------------------------------------------------------------------------------- /pnp4nagios/check_net_traffic.php: -------------------------------------------------------------------------------- 1 | 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy 6 | * of this software and associated documentation files (the "Software"), to deal 7 | * in the Software without restriction, including without limitation the rights 8 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | * copies of the Software, and to permit persons to whom the Software is furnished 10 | * to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | * THE SOFTWARE. 22 | * 23 | * This file is part of the nagios-puppet bundle that can be found 24 | * at https://github.com/jasonhancock/nagios-memory 25 | */ 26 | $alpha = 'CC'; 27 | $colors = array( 28 | '#00FF00' . $alpha, 29 | '#4F7774' . $alpha, 30 | '#88008A' . $alpha, 31 | '#25345C' . $alpha, 32 | ); 33 | $opt[1] = sprintf('-T 55 -l 0 --vertical-label "Bytes" --title "%s / Network Traffic"', $hostname); 34 | $def[1] = ''; 35 | $count = 0; 36 | foreach ($DS as $i) { 37 | $def[1] .= rrd::def("var$i", $rrdfile, $DS[$i], 'AVERAGE'); 38 | //$def[1] .= rrd::area ("var$i", $colors[$count], rrd::cut(ucfirst($NAME[$i]), 15), 'STACK'); 39 | 40 | if ($i == '1') { 41 | $def[1] .= rrd::area ("var$i", $colors[$count], rrd::cut(ucfirst($NAME[$i]), 15)); 42 | } else { 43 | $def[1] .= rrd::area ("var$i", $colors[$count], rrd::cut(ucfirst($NAME[$i]), 15), 'STACK'); 44 | } 45 | 46 | $def[1] .= rrd::gprint ("var$i", array('LAST','MAX','AVERAGE'), "%4.2lf %s\t"); 47 | $count++; 48 | } 49 | -------------------------------------------------------------------------------- /pnp4nagios/check_nowsms.php: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /pnp4nagios/check_tcp_stat.php: -------------------------------------------------------------------------------- 1 | 62 | -------------------------------------------------------------------------------- /setup/nagios/centos-pnp4nagios.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #centos nagios pnp4nagios一键安装脚本 3 | #作者:章郎虫 4 | #博客:http://www.sijitao.net/ 5 | 6 | cd /usr/local/src 7 | 8 | if [ -s pnp4nagios-0.6.24.tar.gz ]; then 9 | echo "pnp4nagios-0.6.24.tar.gz [found]" 10 | else 11 | wget http://sourceforge.net/projects/pnp4nagios/files/PNP-0.6/pnp4nagios-0.6.24.tar.gz 12 | fi 13 | 14 | echo "============================install pnp4nagios===========================" 15 | 16 | sleep 5 17 | 18 | yum install -y rrdtool rrdtool-perl perl-Time-HiRes 19 | 20 | #install gd 21 | yum install -y php-gd 22 | 23 | sleep 5 24 | 25 | tar zxvf pnp4nagios-0.6.24.tar.gz 26 | cd pnp4nagios-0.6.24 27 | ./configure --with-nagios-user=nagios --with-nagios-group=nagcmd 28 | make all 29 | make install 30 | make install-webconf 31 | make install-config 32 | make install-init 33 | 34 | sed -i 's/process_performance_data=0/process_performance_data=1/g' /usr/local/nagios/etc/nagios.cfg 35 | 36 | cat >>/usr/local/nagios/etc/nagios.cfg<<"EOF" 37 | # service performance data 38 | service_perfdata_file=/usr/local/pnp4nagios/var/service-perfdata 39 | service_perfdata_file_template=DATATYPE::SERVICEPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tSERVICEDESC::$SERVICEDESC$\tSERVICEPERFDATA::$SERVICEPERFDATA$\tSERVICECHECKCOMMAND::$SERVICECHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$\tSERVICESTATE::$SERVICESTATE$\tSERVICESTATETYPE::$SERVICESTATETYPE$ 40 | service_perfdata_file_mode=a 41 | service_perfdata_file_processing_interval=15 42 | service_perfdata_file_processing_command=process-service-perfdata-file 43 | 44 | # host performance data starting with Nagios 3.0 45 | host_perfdata_file=/usr/local/pnp4nagios/var/host-perfdata 46 | host_perfdata_file_template=DATATYPE::HOSTPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tHOSTPERFDATA::$HOSTPERFDATA$\tHOSTCHECKCOMMAND::$HOSTCHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$ 47 | host_perfdata_file_mode=a 48 | host_perfdata_file_processing_interval=15 49 | host_perfdata_file_processing_command=process-host-perfdata-file 50 | 51 | EOF 52 | 53 | sleep 1 54 | cat >>/usr/local/nagios/etc/objects/commands.cfg<<"EOF" 55 | define command{ 56 | command_name process-service-perfdata-file 57 | command_line /bin/mv /usr/local/pnp4nagios/var/service-perfdata /usr/local/pnp4nagios/var/spool/service-perfdata.$TIMET$ 58 | } 59 | 60 | define command{ 61 | command_name process-host-perfdata-file 62 | command_line /bin/mv /usr/local/pnp4nagios/var/host-perfdata /usr/local/pnp4nagios/var/spool/host-perfdata.$TIMET$ 63 | } 64 | 65 | EOF 66 | 67 | sleep 1 68 | cat >>/usr/local/nagios/etc/objects/templates.cfg<<"EOF" 69 | define host { 70 | name host-pnp 71 | action_url /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=_HOST_ 72 | register 0 73 | } 74 | 75 | define service { 76 | name srv-pnp 77 | action_url /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=$SERVICEDESC$ 78 | register 0 79 | } 80 | EOF 81 | 82 | chkconfig npcd on 83 | /etc/init.d/npcd start 84 | 85 | #config pnp4nagios to apache 86 | cat > /etc/httpd/conf.d/pnp4nagios.conf< 89 | AllowOverride None 90 | Order allow,deny 91 | Allow from all 92 | AuthName "Nagios Access" 93 | AuthType Basic 94 | AuthUserFile /usr/local/nagios/etc/htpasswd.users 95 | Require valid-user 96 | 97 | # Turn on URL rewriting 98 | RewriteEngine On 99 | Options symLinksIfOwnerMatch 100 | # Installation directory 101 | RewriteBase /pnp4nagios/ 102 | # Protect application and system files from being viewed 103 | RewriteRule "^(?:application|modules|system)/" - [F] 104 | # Allow any files or directories that exist to be displayed directly 105 | RewriteCond "%{REQUEST_FILENAME}" !-f 106 | RewriteCond "%{REQUEST_FILENAME}" !-d 107 | # Rewrite all other URLs to index.php/URL 108 | RewriteRule "^.*$" "index.php/$0" [PT] 109 | 110 | 111 | EOF 112 | /etc/init.d/httpd restart 113 | rm -rf /usr/local/pnp4nagios/share/install.php 114 | -------------------------------------------------------------------------------- /setup/nagios/centos6-nagios-server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #Date: 2015/12/17 3 | #BY:renzhenxing 4 | #EDIT:zhangnq 5 | #BLOG:http://www.sijitao.net/ 6 | #install nagios-server or nagios-plugs 7 | 8 | read -p "Please input your nagiosadmin's password:" a 9 | selinux=`grep SELINUX=enforcing /etc/selinux/config | awk -F "=" '{print $2}'` 10 | 11 | if [ "$selinux" == "enforcing" ] 12 | then 13 | echo "your system Selinux not shut down," 14 | exit 1 15 | fi 16 | 17 | yum install -y httpd php 18 | 19 | yum install -y wget gcc gcc++ gcc* bc net-snmp net-snmp-utils net-snmp-libs libpng libpng-devel libjpeg libjpeg-devel openssl098e gd* gd2* openssl-devel* openssl* 20 | 21 | cd /usr/local/src 22 | 23 | if [ -f nagios-4.0.8.tar.gz ] 24 | then 25 | echo ".........................................nagios.tar.gz..................is OK!!!" 26 | else 27 | echo "nagios.tar.gz.............................is not ok!!!..................download" 28 | wget http://jaist.dl.sourceforge.net/project/nagios/nagios-4.x/nagios-4.0.8/nagios-4.0.8.tar.gz 29 | fi 30 | 31 | #http://www.nagios-plugins.org/download/nagios-plugins-2.1.1.tar.gz 32 | if [ -f nagios-plugins-2.1.1.tar.gz ] 33 | then 34 | echo "............................................nagios-plugs .................is ok!!!" 35 | else 36 | echo "nagios-plugins-2.1.1.tar.gz....................is not ok !!!! ..............download" 37 | wget https://www.nagios-plugins.org/download/nagios-plugins-2.1.1.tar.gz 38 | fi 39 | 40 | if [ -f nrpe-2.15.tar.gz ] 41 | then 42 | echo "............................................nrpe-2.15.tar.gz.................is ok!!!" 43 | else 44 | echo "..................................nrpe-2.15.tar.gz...is not ok!!!............download" 45 | wget http://jaist.dl.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.15/nrpe-2.15.tar.gz 46 | fi 47 | 48 | 49 | ###add install nagios ID: 50 | useradd -m nagios 51 | echo "nagios" | passwd --stdin nagios 52 | 53 | ###add install gid: 54 | groupadd nagcmd 55 | 56 | ###daemon 为apache运行账号: 57 | usermod -a -G nagcmd daemon 58 | 59 | ###install nagios-4.0.8.tar.gz 60 | tar -zxf nagios-4.0.8.tar.gz && cd nagios-4.0.8 61 | ./configure --with-command-group=nagcmd --with-gd-lib=/usr/local/libgd/lib/ --with-gd-inc=/usr/local/libgd/include/ 62 | make all 63 | make install 64 | make install-init 65 | make install-config 66 | make install-commandmode 67 | cd ../ 68 | 69 | cat >>/etc/httpd/conf/httpd.conf< 73 | # SSLRequireSSL 74 | Options ExecCGI 75 | AllowOverride None 76 | Order allow,deny 77 | Allow from all 78 | # Order deny,allow 79 | # Deny from all 80 | # Allow from 127.0.0.1 81 | AuthName "Nagios Access" 82 | AuthType Basic 83 | AuthUserFile /usr/local/nagios/etc/htpasswd.users 84 | Require valid-user 85 | 86 | Alias /nagios "/usr/local/nagios/share" 87 | 88 | # SSLRequireSSL 89 | Options None 90 | AllowOverride None 91 | Order allow,deny 92 | Allow from all 93 | # Order deny,allow 94 | # Deny from all 95 | # Allow from 127.0.0.1 96 | AuthName "Nagios Access" 97 | AuthType Basic 98 | AuthUserFile /usr/local/nagios/etc/htpasswd.users 99 | Require valid-user 100 | 101 | EOF 102 | 103 | ########################################################## 104 | 105 | ###location nagios admin password(default:che100): 106 | htpasswd -cb /usr/local/nagios/etc/htpasswd.users nagiosadmin $a 107 | 108 | ###service httpd server: 109 | service httpd restart 110 | 111 | ###install nagios-plugs(default:/usr/local/nagios/): 112 | tar -xzf nagios-plugins-2.1.1.tar.gz 113 | cd nagios-plugins-2.1.1 114 | ./configure --with-nagios-user=nagios --with-nagios-group=nagios 115 | make 116 | make install 117 | cd ../ 118 | 119 | ###install nrpe: 120 | tar -zxf nrpe-2.15.tar.gz 121 | cd nrpe-2.15 122 | ./configure && make all && make install-plugin 123 | 124 | ###禁用suexec的功能.此功能对CGI的执行路径进行了限制 125 | setenforce 0 126 | 127 | ###start nagios server: 128 | service nagios restart 129 | 130 | 131 | echo "--------------- nagios server install ok!!!------------------------" 132 | echo " " 133 | echo "--------------service nagios start is start -----------------------" 134 | echo " " 135 | 136 | -------------------------------------------------------------------------------- /setup/nagios/php/ubuntu_php.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm -rf /usr/local/php 4 | 5 | echo "============================install dependency==================================" 6 | 7 | sleep 5 8 | for packages in build-essential gcc g++ make automake autoconf re2c wget cron bzip2 libzip-dev libc6-dev file rcconf flex vim nano bison m4 gawk less make cpp binutils diffutils unzip tar bzip2 libbz2-dev unrar p7zip libncurses5-dev libncurses5 libncurses5-dev libncurses5-dev libtool libevent-dev libpcre3 libpcre3-dev libpcrecpp0 libssl-dev zlibc openssl libsasl2-dev libxml2 libxml2-dev libltdl3-dev libltdl-dev libmcrypt-dev libmysqlclient15-dev zlib1g zlib1g-dev libbz2-1.0 libbz2-dev libglib2.0-0 libglib2.0-dev libpng3 libfreetype6 libfreetype6-dev libjpeg62 libjpeg-dev libpng-dev libpng12-0 libpng12-dev curl libcurl3 libmhash2 libmhash-dev libpq-dev libpq5 gettext libncurses5-dev libjpeg-dev libpng12-dev libxml2-dev zlib1g-dev libfreetype6 libfreetype6-dev libssl-dev libcurl3 libcurl4-gnutls-dev mcrypt libcap-dev ; 9 | do 10 | apt-get install -y $packages --force-yes;apt-get -fy install;apt-get -y autoremove; 11 | done 12 | 13 | echo "============================install php==================================" 14 | 15 | sleep 5 16 | cur_dir=$(pwd) 17 | cd $cur_dir 18 | 19 | #wget http://download.chekiang.info/nagios/setup/nagios/php/php-5.5.18.tar.gz 20 | wget -c http://www.php.net/distributions/php-5.5.18.tar.gz 21 | 22 | tar zxvf php-5.5.18.tar.gz 23 | cd php-5.5.18 24 | ./configure --prefix=/usr/local/php --with-openssl --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --enable-sockets --with-apxs2=/usr/local/apache2/bin/apxs --with-mcrypt --with-config-file-path=/usr/local/php/etc --with-bz2 --enable-maintainer-zts 25 | make 26 | make install 27 | cp php.ini-production /usr/local/php/etc/php.ini 28 | 29 | cat >>/usr/local/apache2/conf/httpd.conf < 31 | AddType application/x-httpd-php .php 32 | AddType application/x-httpd-php-source .phps 33 | 34 | EOF 35 | 36 | echo "============================restart apache==================================" 37 | 38 | sleep 5 39 | /etc/init.d/apache2 stop 40 | sleep 1 41 | /etc/init.d/apache2 start 42 | sleep 5 43 | ps -ef|grep apache 44 | -------------------------------------------------------------------------------- /setup/nagios/setupinit.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin 4 | export PATH 5 | 6 | host='http://192.168.188.104' 7 | 8 | # Check if user is root 9 | if [ $(id -u) != "0" ]; then 10 | echo "Error: You must be root to run this script." 11 | exit 1 12 | fi 13 | 14 | echo "============================add user==================================" 15 | 16 | sleep 3 17 | 18 | #issue=$(cat /etc/issue |awk '{print $2}' |awk -F "." '{print $1$2}') 19 | # 20 | #if [ "$issue" -eq "1004" ];then 21 | # adduser zhangnq 22 | # adduser zhangnq admin 23 | #else 24 | # adduser zhangnq 25 | # adduser zhangnq sudo 26 | #fi 27 | #addgroup appl 28 | #adduser appadmin 29 | #usermod -g appl appadmin 30 | #groupdel appadmin 31 | #chgrp -R appl /home/appadmin 32 | #chmod 750 /home/appadmin 33 | userdel -r administrator 34 | userdel -r user 35 | usermod -p '!' root 36 | 37 | echo "===========================setup default===================================" 38 | 39 | sleep 3 40 | 41 | if [ "$issue" -eq "1004" ];then 42 | wget http://192.168.188.102/mirror/sources.list.lucid -O sources.list 43 | mv /etc/apt/sources.list /etc/apt/source.list.`date "+%Y%m%d%H%M%S"` 44 | mv sources.list /etc/apt/ 45 | fi 46 | if [ "$issue" -eq "1204" ];then 47 | wget http://192.168.188.102/mirror/sources.list.precise -O sources.list 48 | mv /etc/apt/sources.list /etc/apt/source.list.`date "+%Y%m%d%H%M%S"` 49 | mv sources.list /etc/apt/ 50 | fi 51 | 52 | apt-get update 53 | apt-get -y install ntpdate build-essential gcc g++ make zlibc zlib1g zlib1g-dev language-pack-zh-hans 54 | 55 | #set localtime 56 | cat >/etc/cron.daily/ntpdate <>/var/log/ntpdate.log 2>&1 59 | EOF 60 | chmod +x /etc/cron.daily/ntpdate 61 | 62 | #set default language 63 | mv /etc/default/locale /etc/default/locale.`date "+%Y%m%d%H%M%S"` 64 | cat >/etc/default/locale </var/lib/locales/supported.d/local 69 | 70 | #Synchronization time 71 | mv /etc/localtime /etc/localtime.bak 72 | ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 73 | 74 | reboot 75 | -------------------------------------------------------------------------------- /setup/nagios/ubuntu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #ubuntu nagios服务端一键安装脚本 4 | #作者:章郎虫 5 | #博客:http://www.sijitao.net/ 6 | 7 | #check if user is root 8 | if [ $(id -u) != "0" ]; then 9 | echo "Error: You must be root to run this script." 10 | exit 1 11 | fi 12 | 13 | read -p "Do you want to install apache server?Please input yes or no.Default is yes:" is_apache 14 | read -p "Do you want to install php?Please input yes or no.Default is yes:" is_php 15 | read -p "Please input nagios admin password(default username:nagiosadmin):" nagios_pwd 16 | 17 | cur_dir=$(pwd) 18 | cd $cur_dir 19 | 20 | echo "============================check files==================================" 21 | 22 | sleep 5 23 | if [ -s nagios-4.0.8.tar.gz ]; then 24 | echo "nagios-4.0.8.tar.gz [found]" 25 | else 26 | wget -c http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-4.0.8.tar.gz 27 | fi 28 | if [ -s nagios-plugins-2.0.3.tar.gz ]; then 29 | echo "nagios-plugins-2.0.3.tar.gz [found]" 30 | else 31 | wget -c http://nagios-plugins.org/download/nagios-plugins-2.0.3.tar.gz 32 | fi 33 | if [ -s nrpe-2.15.tar.gz ]; then 34 | echo "nrpe-2.15.tar.gz [found]" 35 | else 36 | wget -c http://prdownloads.sourceforge.net/sourceforge/nagios/nrpe-2.15.tar.gz 37 | fi 38 | if [ -s pnp4nagios-0.6.24.tar.gz ]; then 39 | echo "pnp4nagios-0.6.24.tar.gz [found]" 40 | else 41 | wget http://sourceforge.net/projects/pnp4nagios/files/PNP-0.6/pnp4nagios-0.6.24.tar.gz 42 | fi 43 | 44 | echo "============================install dependency============================" 45 | 46 | sleep 5 47 | apt-get update 48 | packages='libgd2-noxpm libgd2-noxpm-dev libssl-dev libssl0.9.8 make openssl sendemail rrdtool librrds-perl' 49 | for package in $packages;do 50 | apt-get -y install $package 51 | done 52 | 53 | echo "============================install apache2 ============================" 54 | 55 | sleep 5 56 | if [ "${is_apache:-yes}" = "yes" ];then 57 | rm -rf /etc/httpd 58 | rm -rf /usr/local/apache2 59 | mkdir -p $cur_dir/apache 60 | cd $cur_dir/apache 61 | wget http://download.chekiang.info/apache/ubuntu_apache.sh 62 | chmod +x ubuntu_apache.sh 63 | ./ubuntu_apache.sh 64 | 65 | /etc/init.d/apache2 stop 66 | fi 67 | 68 | echo "============================install php ============================" 69 | 70 | sleep 5 71 | if [ "${is_php:-yes}" = "yes" ];then 72 | mkdir -p $cur_dir/php 73 | cd $cur_dir/php 74 | wget http://download.chekiang.info/nagios/setup/nagios/php/ubuntu_php.sh 75 | chmod +x ubuntu_php.sh 76 | ./ubuntu_php.sh 77 | fi 78 | 79 | echo "============================install nagios core===========================" 80 | 81 | sleep 5 82 | useradd -m -s /sbin/nologin nagios 83 | groupadd nagcmd 84 | usermod -a -G nagcmd nagios 85 | usermod -a -G nagcmd www 86 | 87 | cd $cur_dir 88 | 89 | tar zxvf nagios-4.0.8.tar.gz 90 | cd nagios-4.0.8 91 | ./configure --with-command-group=nagcmd 92 | make 93 | make all 94 | make install 95 | make install-init 96 | make install-config 97 | make install-commandmode 98 | make install-webconf 99 | 100 | /usr/local/apache2/bin/htpasswd -b -c /usr/local/nagios/etc/htpasswd.users nagiosadmin $nagios_pwd 101 | 102 | echo "============================install nagios plugins===========================" 103 | 104 | sleep 5 105 | cd $cur_dir 106 | tar zxvf nagios-plugins-2.0.3.tar.gz 107 | cd nagios-plugins-2.0.3 108 | ./configure --with-nagios-user=nagios --with-nagios-group=nagios 109 | make 110 | make install 111 | 112 | echo "============================install nrpe===========================" 113 | 114 | sleep 5 115 | cd $cur_dir 116 | tar zxvf nrpe-2.15.tar.gz 117 | cd nrpe-2.15 118 | ./configure --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu 119 | make all 120 | make install-plugin 121 | make install-daemon 122 | make install-daemon-config 123 | 124 | echo "============================start nagios===========================" 125 | #check nagios install 126 | /usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg 127 | 128 | /usr/local/nagios/bin/nagios -d /usr/local/nagios/etc/nagios.cfg 129 | /usr/local/nagios/bin/nagiostats 130 | /usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d 131 | /usr/local/nagios/libexec/check_nrpe -H localhost 132 | 133 | sleep 5 134 | update-rc.d nagios defaults 135 | sed -i '/.*exit 0.*/i\/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d' /etc/rc.local 136 | 137 | echo "============================install pnp4nagios===========================" 138 | 139 | sleep 5 140 | cd $cur_dir 141 | apt-get -y install sendemail rrdtool librrds-perl 142 | 143 | #install gd 144 | cd php/php-5.5.18/ext/gd 145 | /usr/local/php/bin/phpize 146 | ./configure --with-php-config=/usr/local/php/bin/php-config 147 | make 148 | make install 149 | cat >>/usr/local/php/etc/php.ini <>/usr/local/nagios/etc/nagios.cfg<<"EOF" 169 | # service performance data 170 | service_perfdata_file=/usr/local/pnp4nagios/var/service-perfdata 171 | service_perfdata_file_template=DATATYPE::SERVICEPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tSERVICEDESC::$SERVICEDESC$\tSERVICEPERFDATA::$SERVICEPERFDATA$\tSERVICECHECKCOMMAND::$SERVICECHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$\tSERVICESTATE::$SERVICESTATE$\tSERVICESTATETYPE::$SERVICESTATETYPE$ 172 | service_perfdata_file_mode=a 173 | service_perfdata_file_processing_interval=15 174 | service_perfdata_file_processing_command=process-service-perfdata-file 175 | 176 | # host performance data starting with Nagios 3.0 177 | host_perfdata_file=/usr/local/pnp4nagios/var/host-perfdata 178 | host_perfdata_file_template=DATATYPE::HOSTPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tHOSTPERFDATA::$HOSTPERFDATA$\tHOSTCHECKCOMMAND::$HOSTCHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$ 179 | host_perfdata_file_mode=a 180 | host_perfdata_file_processing_interval=15 181 | host_perfdata_file_processing_command=process-host-perfdata-file 182 | 183 | EOF 184 | 185 | sleep 1 186 | cat >>/usr/local/nagios/etc/objects/commands.cfg<<"EOF" 187 | define command{ 188 | command_name process-service-perfdata-file 189 | command_line /bin/mv /usr/local/pnp4nagios/var/service-perfdata /usr/local/pnp4nagios/var/spool/service-perfdata.$TIMET$ 190 | } 191 | 192 | define command{ 193 | command_name process-host-perfdata-file 194 | command_line /bin/mv /usr/local/pnp4nagios/var/host-perfdata /usr/local/pnp4nagios/var/spool/host-perfdata.$TIMET$ 195 | } 196 | 197 | EOF 198 | 199 | sleep 1 200 | cat >>/usr/local/nagios/etc/objects/templates.cfg<<"EOF" 201 | define host { 202 | name host-pnp 203 | action_url /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=_HOST_ 204 | register 0 205 | } 206 | 207 | define service { 208 | name srv-pnp 209 | action_url /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=$SERVICEDESC$ 210 | register 0 211 | } 212 | EOF 213 | 214 | update-rc.d npcd defaults 215 | /etc/init.d/npcd start 216 | 217 | /etc/init.d/apache2 restart 218 | 219 | #echo "============================install init===========================" 220 | #sleep 5 221 | #cd $cur_dir 222 | #./setupinit.sh 223 | -------------------------------------------------------------------------------- /setup/nagios_client/centos.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #Date: 2015/12/17 3 | #BY:zhangnq 4 | #BLOG:http://www.sijitao.net/ 5 | #install nagios-plugs nagios-nrpe 6 | 7 | mkdir /usr/local/nagios 8 | /usr/sbin/useradd -m -s/sbin/nologin nagios 9 | chown nagios.nagios /usr/local/nagios/ 10 | groupadd nagcmd 11 | usermod -a -G nagcmd nagios 12 | 13 | yum groupinstall -y "Development Tools" 14 | yum install -y gcc make openssl openssl-devel bc 15 | 16 | cd /usr/local/src 17 | 18 | if [ -f nagios-plugins-2.1.1.tar.gz ] 19 | then 20 | echo "............................................nagios-plugs .................is ok!!!" 21 | else 22 | echo "nagios-plugins-2.1.1.tar.gz....................is not ok !!!! ..............download" 23 | wget https://www.nagios-plugins.org/download/nagios-plugins-2.1.1.tar.gz 24 | fi 25 | 26 | if [ -f nrpe-2.15.tar.gz ] 27 | then 28 | echo "............................................nrpe-2.15.tar.gz.................is ok!!!" 29 | else 30 | echo "..................................nrpe-2.15.tar.gz...is not ok!!!............download" 31 | wget http://jaist.dl.sourceforge.net/project/nagios/nrpe-2.x/nrpe-2.15/nrpe-2.15.tar.gz 32 | fi 33 | 34 | tar zxvf nagios-plugins-2.1.1.tar.gz 35 | cd nagios-plugins-2.1.1 36 | ./configure --with-nagios-user=nagios --with-nagios-group=nagios --prefix=/usr/local/nagios 37 | make && make install 38 | chown -R nagios.nagios /usr/local/nagios/libexec 39 | cd .. 40 | 41 | tar zxvf nrpe-2.15.tar.gz 42 | cd nrpe-2.15 43 | ./configure --with-ssl=/usr/bin/openssl 44 | make all 45 | make install 46 | make install-plugin 47 | make install-daemon 48 | make install-daemon-config 49 | cd .. 50 | sed -i 's/allowed_hosts=.*/allowed_hosts=127.0.0.1/g' /usr/local/nagios/etc/nrpe.cfg 51 | cnt=`grep -c "/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d" /etc/rc.local` 52 | if [ $cnt -eq 0 ];then 53 | #sed -i '/.*exit 0.*/i\/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d' /etc/rc.local 54 | echo "/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d" >>/etc/rc.local 55 | fi 56 | cat >>/usr/local/nagios/etc/nrpe.cfg<<"EOF" 57 | command[check_swap]=/usr/local/nagios/libexec/check_swap -w 90% -c 60% 58 | command[check_/]=/usr/local/nagios/libexec/check_disk -w 20% -c 10% -p / 59 | EOF 60 | 61 | /usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d 62 | 63 | cd /root 64 | 65 | cat >restart_nrpe.sh<<"EOF" 66 | #!/bin/bash 67 | export PATH="$PATH" 68 | killall nrpe 69 | /usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d 70 | sleep 1 71 | ps -ef|grep nagios 72 | EOF 73 | chmod +x restart_nrpe.sh 74 | 75 | #install nagios plugins 76 | cd /usr/local/nagios/libexec 77 | wget https://raw.githubusercontent.com/zhangnq/nagios/master/check_tcp_stat.sh 78 | chmod +x check_tcp_stat.sh 79 | chown nagios:nagios check_tcp_stat.sh 80 | wget https://raw.githubusercontent.com/zhangnq/nagios/master/check_mem.sh 81 | chmod +x check_mem.sh 82 | chown nagios:nagios check_mem.sh 83 | wget https://raw.githubusercontent.com/zhangnq/nagios/master/check_net_traffic.sh 84 | chmod +x check_net_traffic.sh 85 | chown nagios:nagios check_net_traffic.sh 86 | 87 | cat >>/usr/local/nagios/etc/nrpe.cfg<<"EOF" 88 | command[check_tcp_stat]=/usr/local/nagios/libexec/check_tcp_stat.sh -w 100 -c 200 89 | command[check_mem]=/usr/local/nagios/libexec/check_mem.sh -w 80% -c 90% 90 | command[check_net_traffic]=/usr/local/nagios/libexec/check_net_traffic.sh -d eth0 -w 5M -c 20M 91 | EOF 92 | sleep 3 93 | /root/restart_nrpe.sh 94 | 95 | -------------------------------------------------------------------------------- /setup/nagios_client/ubuntu.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | #ubuntu nagios客户端一键安装脚本 4 | #作者:章郎虫 5 | #博客:http://www.sijitao.net/ 6 | 7 | mkdir /usr/local/nagios 8 | /usr/sbin/useradd -m -s/sbin/nologin nagios 9 | chown nagios.nagios /usr/local/nagios/ 10 | groupadd nagcmd 11 | usermod -a -G nagcmd nagios 12 | 13 | apt-get -y install build-essential gcc libssl-dev libssl0.9.8 make openssl 14 | apt-get -y install bc 15 | 16 | wget http://download.chekiang.info/nagios/setup/nagios_client/nagios-plugins-2.0.3.tar.gz 17 | 18 | tar zxvf nagios-plugins-2.0.3.tar.gz 19 | cd nagios-plugins-2.0.3 20 | ./configure --with-nagios-user=nagios --with-nagios-group=nagios --prefix=/usr/local/nagios 21 | make && make install 22 | chown -R nagios.nagios /usr/local/nagios/libexec 23 | cd .. 24 | 25 | wget http://download.chekiang.info/nagios/setup/nagios_client/nrpe-2.15.tar.gz 26 | 27 | tar zxvf nrpe-2.15.tar.gz 28 | cd nrpe-2.15 29 | ./configure --with-ssl=/usr/bin/openssl --with-ssl-lib=/usr/lib/x86_64-linux-gnu 30 | make all 31 | make install 32 | make install-plugin 33 | make install-daemon 34 | make install-daemon-config 35 | cd .. 36 | sed -i 's/allowed_hosts=.*/allowed_hosts=127.0.0.1/g' /usr/local/nagios/etc/nrpe.cfg 37 | cnt=`grep -c "/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d" /etc/rc.local` 38 | if [ $cnt -eq 0 ];then 39 | sed -i '/.*exit 0.*/i\/usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d' /etc/rc.local 40 | fi 41 | 42 | cat >>/usr/local/nagios/etc/nrpe.cfg<<"EOF" 43 | command[check_swap]=/usr/local/nagios/libexec/check_swap -w 90% -c 60% 44 | command[check_/]=/usr/local/nagios/libexec/check_disk -w 20% -c 10% -p / 45 | command[check_mem]=/usr/local/nagios/libexec/check_mem.sh -w 90 -c 95 46 | command[check_tcp_stat]=/usr/local/nagios/libexec/check_tcp_stat.sh -w 5000 -c 8000 47 | command[check_net_traffic]=/usr/local/nagios/libexec/check_net_traffic.sh -d eth0 -w 5M -c 10M 48 | EOF 49 | 50 | cd /usr/local/nagios/libexec 51 | wget https://raw.githubusercontent.com/zhangnq/nagios/master/check_mem.sh --no-check-certificate 52 | chmod +x check_mem.sh 53 | wget https://raw.githubusercontent.com/zhangnq/nagios/master/check_net_traffic.sh --no-check-certificate 54 | chmod +x check_net_traffic.sh 55 | wget https://raw.githubusercontent.com/zhangnq/nagios/master/check_tcp_stat.sh --no-check-certificate 56 | chmod +x check_tcp_stat.sh 57 | 58 | 59 | /usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d 60 | 61 | cat >/root/restart_nrpe.sh<<"EOF" 62 | #!/bin/bash 63 | export PATH="$PATH" 64 | killall nrpe 65 | /usr/local/nagios/bin/nrpe -c /usr/local/nagios/etc/nrpe.cfg -d 66 | sleep 1 67 | ps -ef|grep nagios 68 | EOF 69 | chmod +x /root/restart_nrpe.sh 70 | 71 | 72 | -------------------------------------------------------------------------------- /setup/submit_host_check_result: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Arguments: 3 | # $1 = host_name (Short name of host that the service is associated with) 4 | # $2 = svc_description (Description of the service) 5 | # $3 = state_string (A string representing the status of the given service - "OK", "WARNING", "CRITICAL" or "UNKNOWN") 6 | # $4 = plugin_output (A text string that should be used as the plugin output for the service checks) 7 | # 8 | # Convert the state string to the corresponding return code 9 | 10 | return_code=-1 11 | case "$2" in 12 | UP) 13 | return_code=0 14 | ;; 15 | DOWN) 16 | return_code=1 17 | ;; 18 | UNREACHABLE) 19 | return_code=2 20 | ;; 21 | UNKNOWN) 22 | return_code=-1 23 | ;; 24 | esac 25 | 26 | /usr/bin/printf "%s\t%s\t%s\n" "$1" "$return_code" "$3" | /usr/local/nagios/bin/send_nsca www.chekiang.info -c /usr/local/nagios/etc/send_nsca.cfg 27 | -------------------------------------------------------------------------------- /setup/submit_service_check_result: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Arguments: 3 | # $1 = host_name (Short name of host that the service is associated with) 4 | # $2 = svc_description (Description of the service) 5 | # $3 = state_string (A string representing the status of the given service - "OK", "WARNING", "CRITICAL" or "UNKNOWN") 6 | # $4 = plugin_output (A text string that should be used as the plugin output for the service checks) 7 | # 8 | # Convert the state string to the corresponding return code 9 | 10 | return_code=-1 11 | case "$3" in 12 | OK) 13 | return_code=0 14 | ;; 15 | WARNING) 16 | return_code=1 17 | ;; 18 | CRITICAL) 19 | return_code=2 20 | ;; 21 | UNKNOWN) 22 | return_code=-1 23 | ;; 24 | esac 25 | 26 | # pipe the service check info into the send_nsca program, which in turn transmits the data to the nsca daemon on the central monitoring server 27 | 28 | /usr/bin/printf "%s\t%s\t%s\t%s\n" "$1" "$2" "$return_code" "$4" | /usr/local/nagios/bin/send_nsca www.chekiang.info -c /usr/local/nagios/etc/send_nsca.cfg 29 | -------------------------------------------------------------------------------- /weixin/NotifyByWeixin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #coding:utf-8 3 | 4 | import urllib2 5 | import urllib 6 | import json 7 | from config import * 8 | import pickle 9 | import datetime,time 10 | import argparse 11 | 12 | def url_request(url,values={},method='GET'): 13 | if method == 'GET': 14 | if len(values) != 0: 15 | url_values=urllib.urlencode(values) 16 | furl=url+'?'+url_values 17 | else: 18 | furl=url 19 | req=urllib2.Request(furl) 20 | elif method == 'POST': 21 | #data=urllib.urlencode(values) 22 | try: 23 | data=json.dumps(values,ensure_ascii=True) 24 | except: 25 | import sys 26 | sys_encoding=sys.stdin.encoding 27 | data=json.dumps(values,ensure_ascii=True,encoding=sys_encoding) 28 | 29 | req=urllib2.Request(url,data) 30 | req.add_header('Content-Type','application/json') 31 | req.get_method=lambda: 'POST' 32 | else: 33 | pass 34 | 35 | try: 36 | req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36') 37 | response = urllib2.urlopen(req) 38 | result=json.loads(response.read()) 39 | except urllib2.URLError as e: 40 | if hasattr(e, 'code'): 41 | print 'Error code:',e.code 42 | elif hasattr(e, 'reason'): 43 | print 'Reason:',e.reason 44 | 45 | result={} 46 | except: 47 | result={} 48 | 49 | return result 50 | 51 | def get_token(): 52 | data_pkl='token_data.pkl' 53 | try: 54 | f=file(data_pkl,'rb') 55 | data_dict=pickle.load(f) 56 | f.close() 57 | except: 58 | data_dict={} 59 | try: 60 | expires_time=data_dict['expires_time'] 61 | except: 62 | expires_time=0 63 | now_time=int(time.mktime(datetime.datetime.now().timetuple())) 64 | if now_time >= expires_time: 65 | url='https://qyapi.weixin.qq.com/cgi-bin/gettoken' 66 | values={ 67 | 'corpid':CorpID, 68 | 'corpsecret':Secret, 69 | } 70 | result=url_request(url, values, method='GET') 71 | if len(result) != 0: 72 | now_time=int(time.mktime(datetime.datetime.now().timetuple())) 73 | expires_time=now_time+7200-10 74 | result['expires_time']=expires_time 75 | f=file(data_pkl,'wb') 76 | pickle.dump(result,f) 77 | f.close() 78 | access_token=result['access_token'] 79 | else: 80 | print "Get token error,exit!" 81 | access_token='' 82 | else: 83 | access_token=data_dict['access_token'] 84 | 85 | 86 | return access_token 87 | 88 | def send_text_message(token,content): 89 | url='https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+token+'&debug='+str(DEBUG) 90 | content_data=content.split('-@@-') 91 | notify_type=content_data[0] 92 | if notify_type == 'host': 93 | type1=content_data[1] 94 | host_name=content_data[2] 95 | host_state=content_data[3] 96 | host_address=content_data[4] 97 | host_info=content_data[5] 98 | notify_contact=content_data[6] 99 | notify_content="** Nagios **\n\nNotification Type: "+ type1 + \ 100 | "\nHost: " + host_name + \ 101 | "\nState: " + host_state + \ 102 | "\nAddress: " + host_address + \ 103 | "\nInfo: " + host_info + "\n" 104 | elif notify_type == 'service': 105 | type1=content_data[1] 106 | service_desc=content_data[2] 107 | host_name=content_data[3] 108 | host_address=content_data[4] 109 | service_state=content_data[5] 110 | service_info=content_data[6] 111 | notify_contact=content_data[7] 112 | notify_content="** Nagios **\n\nNotification Type: "+ type1 + \ 113 | "\nService: " + service_desc + \ 114 | "\nHost: " + host_name + \ 115 | "\nAddress: " + host_address + \ 116 | "\nState: " + service_state + \ 117 | "\nInfo: " + service_info + "\n" 118 | else: 119 | notify_content="Get nagios message notify info error.\n\nContent: %s" % content 120 | notify_contact=ToUser 121 | 122 | values={ 123 | "touser":notify_contact, 124 | #"toparty":ToParty, 125 | "msgtype": "text", 126 | "agentid": AgentId, 127 | "text": { 128 | "content": notify_content 129 | }, 130 | } 131 | return url_request(url, values, method='POST') 132 | 133 | def main(): 134 | token=get_token() 135 | parser=argparse.ArgumentParser(description="Nagios notify by weixin") 136 | parser.add_argument("content",default=None,help="notify content,split with -@@-") 137 | args = parser.parse_args() 138 | 139 | content=args.content 140 | send_text_message(token, content) 141 | 142 | if __name__ == "__main__": 143 | #token = get_token() 144 | #content=u"host-@@-111-@@-222-@@-333-@@-444-@@-测试-@@-zhangnq" 145 | #send_text_message(token, content) 146 | main() 147 | 148 | -------------------------------------------------------------------------------- /weixin/README.md: -------------------------------------------------------------------------------- 1 | #nagios 微信通知脚本 2 | 3 | 使用前需要去微信公众平台申请一个企业号。 4 | 5 | ##使用 6 | 7 | ###配置 8 | config.py 9 | 10 | 内容类似如下: 11 | 12 | >CorpID='your corpid' 13 | >Secret='your secret' 14 | >DEBUG=0 15 | >ToUser='xxx' //系统管理员,默认用户 16 | >AgentId=1 17 | 18 | ###运行 19 | 20 | >python NotifyByWeixin.py 通知内容 21 | 22 | 其中通知内容格式分别为: 23 | 24 | 主机通知:"host-@@-111-@@-222-@@-333-@@-444-@@-555-@@-666" 25 | 26 | >111:通知类型 27 | >222:主机名称 28 | >333:主机状态 29 | >444:主机地址 30 | >555:主机详细信息 31 | >666:通知联系人 32 | 33 | 服务通知:"service-@@-111-@@-222-@@-333-@@-444-@@-555-@@-666-@@-777" 34 | 35 | >111:通知类型 36 | >222:服务描述 37 | >333:主机名称 38 | >444:主机地址 39 | >555:服务状态 40 | >666:服务详细信息 41 | >777:通知联系人 42 | 43 | ###配置 44 | 45 | 下载脚本到nagios目录,例如/usr/local/nagios/python/weixin,修改config.py配置文件。 46 | 47 | nagios配置 48 | 49 | commands.cfg命令文件中添加weixin命令: 50 | 51 | >define command{ 52 | > command_name notify-host-by-weixin 53 | > command_line /usr/local/nagios/python/weixin/NotifyByWeixin.py "host-@@-$NOTIFICATIONTYPE$-@@-$HOSTNAME$-@@-$HOSTSTATE$-@@-$HOSTADDRESS$-@@-$HOSTOUTPUT$-@@-$CONTACTALIAS$" 54 | >} 55 | >define command{ 56 | > command_name notify-service-by-weixin 57 | > command_line /usr/local/nagios/python/weixin/NotifyByWeixin.py "service-@@-$NOTIFICATIONTYPE$-@@-$SERVICEDESC$-@@-$HOSTALIAS$-@@-$HOSTADDRESS$-@@-$SERVICESTATE$-@@-$SERVICEOUTPUT$-@@-$CONTACTALIAS$" 58 | >} 59 | 60 | templates.cfg模板文件中添加联系人模板: 61 | 62 | >define contact{ 63 | > name weixin-contact 64 | > service_notification_period 24x7 65 | > host_notification_period 24x7 66 | > service_notification_options w,u,c,r,f,s 67 | > host_notification_options d,u,r,f,s 68 | > service_notification_commands notify-service-by-weixin 69 | > host_notification_commands notify-host-by-weixin 70 | > register 0 71 | >} 72 | 73 | contacts.cfg联系人中添加微信通知联系人,例如: 74 | 75 | >define contact{ 76 | > contact_name zhangnq-weixin 77 | > use weixin-contact 78 | > alias zhangnq 79 | > email admin@nbhao.org 80 | >} 81 | 82 | 最后在配置service的时候添加zhangnq-weixin这个联系人后就可以通过微信发送报警邮件了。 83 | 84 | -------------------------------------------------------------------------------- /weixin/config-sample.py: -------------------------------------------------------------------------------- 1 | #coding:utf-8 2 | 3 | CorpID='xxxxx' 4 | Secret='xxxxxxxxxxxxxxxxx' 5 | 6 | DEBUG=0 7 | 8 | ToUser='zhangnq' 9 | AgentId=1 --------------------------------------------------------------------------------