commit a52829f96c1c48cecb0ed0fd9ff34540880fe3db Author: Chl Date: Tue Jul 23 22:28:09 2019 +0200 Commit initial: récupération et tri rapide diff --git a/Makefile-dnssec-nsec3 b/Makefile-dnssec-nsec3 new file mode 100644 index 0000000..2f484c9 --- /dev/null +++ b/Makefile-dnssec-nsec3 @@ -0,0 +1,15 @@ +# For NSEC3 records, we need 8 random bytes, which means a 16 hexa string +SALT := $(shell dd if=/dev/random bs=13 count=1 2>/dev/null | hexdump -v -e '"%02x"' | cut -c 1-16 ) + +# There's no easy way to know if bind has been reloaded +# after the .signed file has been generated so it will +# always reload actually. +reload: db.*.signed + service bind9 reload + # Ou nsdc rebuild && nsdc reload pour NSD + +db.%.signed: db.% + @echo Signing requires a lot of entropy in /dev/random, do not hesitate to load the machine... + # 5356800 seconds = two months of validity + #dnssec-signzone -e +5356800 $^ + dnssec-signzone -e +7776000 -o $* -K ../keys/ -3 $(SALT) $^ diff --git a/apt-conf-proxy.sh b/apt-conf-proxy.sh new file mode 100755 index 0000000..a567643 --- /dev/null +++ b/apt-conf-proxy.sh @@ -0,0 +1,13 @@ +#!/bin/sh + +# À utiliser en mettant la ligne suivante dans le fichier : /etc/apt/apt.conf.d/44proxy +# Acquire::http::Proxy-Auto-Detect "/usr/local/share/scripts-admin/apt-conf-proxy.sh"; + +PROXY_HOST=apt-proxy.example.net +PROXY_PORT=3142 + +if nc -zw1 $PROXY_HOST $PROXY_PORT 2>/dev/null >/dev/null; then + echo http://$PROXY_HOST:$PROXY_PORT/ +else + echo DIRECT +fi diff --git a/fail2ban-mail-nocommand-dirty.sh b/fail2ban-mail-nocommand-dirty.sh new file mode 100755 index 0000000..c840d1b --- /dev/null +++ b/fail2ban-mail-nocommand-dirty.sh @@ -0,0 +1,12 @@ +#!/bin/sh + +# Création de la chaîne si elle n'existe pas +iptables-save | grep auth2ban >/dev/null 2>&1 || ( iptables -N auth2ban ; iptables -I INPUT 2 -j auth2ban ) + +# Vidange +iptables -F auth2ban + +# Remplissage +tail -n 3000 /var/log/syslog | grep "did not issue MAIL/EXPN/VRFY/ETRN during connection" | sed -n 's/.*\[\([0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\)\] .*/\1/p' | sort | uniq -c | grep -v "^[[:space:]]*1 " | awk '{ print $2 }' | while read LINE; do + iptables -A auth2ban -s "$LINE" -j DROP +done diff --git a/hooks-git/mantis-filename-commitmsg_pre-receive b/hooks-git/mantis-filename-commitmsg_pre-receive new file mode 100755 index 0000000..3d4b57d --- /dev/null +++ b/hooks-git/mantis-filename-commitmsg_pre-receive @@ -0,0 +1,83 @@ +#!/bin/sh + +# This pre-receive hook is meant to be put in the main +# repository of the project to detect if a commit follow +# the rule for database updates. +# For example, with the issue #123, second script : +# - adding the file scripts/script_123-2.sql +# - putting the filename in the commit msg for easier retrieval + +# When encountering non-UTF8 messages commit, sed may fail. +LANG=C +# Small attemp at making this script portable... +PATH_SCRUTINIZED="scripts" + +# We fail on all uncaught errors +# and it helps us transmit error status outside +# of the loops +set -e + +while read LINE; do + oldrev="$( echo $LINE | cut -f 1 -d ' ' )" + newrev="$( echo $LINE | cut -f 2 -d ' ' )" + refname="$( echo $LINE | cut -f 3 -d ' ' )" + + # We ignore refs/tags and refs/remotes + if ! echo "$refname" | grep "^refs/heads/" >/dev/null; then + continue + fi + + # In case oldrev is "000000..." + if [ "$oldrev" = "0000000000000000000000000000000000000000" ]; then + period="$newrev" + else + period="$oldrev..$newrev" + fi + + # We loop over each commit to check if they + # put a script file to the scripts/ directory + # without having the following format in the + # first line of the commit message : + # [NNNN-NN-SQL] blabla... bla... + git log --pretty=oneline "$period" -- "$PATH_SCRUTINIZED" | while read COMMIT; do + # Commit metadata extraction + commitsha="$( echo "$COMMIT" | sed 's/^\([^ ]\+\) \(.*\)$/\1/' )" + commitmsg="$( echo "$COMMIT" | sed 's/^\([^ ]\+\) \(.*\)$/\2/' )" + + # Listing of files modified by commit + # (git diff-tree will escape tab and other shell-risky characters, but not spaces) + IFS="$( printf "\t\n" )" + for filename in $( git diff-tree --no-commit-id --name-only --root -r "$commitsha" ); do + if echo "$filename" | grep "^$PATH_SCRUTINIZED/script"; then + # Check the filename is well-formed + if ! echo "$filename" | egrep "^$PATH_SCRUTINIZED/script_[0-9]{4,5}-[0-9]{2}.(sql|php)$" >/dev/null; then + echo "check-scripts: nom de fichier non conforme : $filename" + exit 1 + fi + + # Check the filename matches the commit message + mantis_number="$( echo "$filename" | sed -n 's#.*/script_\([0-9]\+\)-\([0-9]\+\).\(sql\|php\)#\1#p' )" + script_number="$( echo "$filename" | sed -n 's#.*/script_\([0-9]\+\)-\([0-9]\+\).\(sql\|php\)#\2#p' )" + extension="$( echo "$filename" | sed -n 's#.*/script_\([0-9]\+\)-\([0-9]\+\).\(sql\|php\)#\3#p' | tr "a-z" "A-Z" )" + if ! echo $commitmsg | grep "\[$mantis_number-$script_number-$extension\] " >/dev/null; then + echo "check-scripts: message de commit non conforme au script (filename : $filename) ($commitsha) : $commitmsg" + exit 1 + fi + fi + done + + # Inversely, for every commit message with the correct format, we + # check the matching file exists + if echo "$commitmsg" | egrep "^\[[0-9-]+[A-Z]{3}\]" >/dev/null; then + # Check the filename matches the commit message + mantis_number="$( echo "$commitmsg" | sed -n 's#^\[\([0-9]\{4,5\}\)-\([0-9]\{2\}\)-\(SQL\|PHP\)\] .*#\1#p' )" + script_number="$( echo "$commitmsg" | sed -n 's#^\[\([0-9]\{4,5\}\)-\([0-9]\{2\}\)-\(SQL\|PHP\)\] .*#\2#p' )" + extension="$( echo "$commitmsg" | sed -n 's#^\[\([0-9]\{4,5\}\)-\([0-9]\{2\}\)-\(SQL\|PHP\)\] .*#\3#p' | tr "A-Z" "a-z" )" + if [ -z "$mantis_number" ] || ! git diff-tree --no-commit-id --name-only --root -r "$commitsha" | grep "^$PATH_SCRUTINIZED/script_$mantis_number-$script_number.$extension$" >/dev/null; then + echo "check-scripts: aucun script SQL/PHP correspondant au message de commit ($commitsha) : $commitmsg" + exit 1 + fi + fi + + done +done diff --git a/hooks-git/simple-php-checks_pre-commit b/hooks-git/simple-php-checks_pre-commit new file mode 100755 index 0000000..2da9e10 --- /dev/null +++ b/hooks-git/simple-php-checks_pre-commit @@ -0,0 +1,58 @@ +#!/bin/sh +# +# An example hook script to verify what is about to be committed. +# Called by "git commit" with no arguments. The hook should +# exit with non-zero status after issuing an appropriate message if +# it wants to stop the commit. +# +# To enable this hook, rename this file to "pre-commit". + +if git rev-parse --verify HEAD >/dev/null 2>&1 +then + against=HEAD +else + # Initial commit: diff against an empty tree object + against=4b825dc642cb6eb9a060e54bf8d69288fbee4904 +fi + +# If you want to allow non-ASCII filenames set this variable to true. +allownonascii=$(git config --bool hooks.allownonascii) + +# Redirect output to stderr. +exec 1>&2 + +# Cross platform projects tend to avoid non-ASCII filenames; prevent +# them from being added to the repository. We exploit the fact that the +# printable range starts at the space character and ends with tilde. +if [ "$allownonascii" != "true" ] && + # Note that the use of brackets around a tr range is ok here, (it's + # even required, for portability to Solaris 10's /usr/bin/tr), since + # the square bracket bytes happen to fall in the designated range. + test $(git diff --cached --name-only --diff-filter=A -z $against | + LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 +then + cat <<\EOF +Error: Attempt to add a non-ASCII file name. + +This can cause problems if you want to work with people on other platforms. + +To be portable it is advisable to rename the file. + +If you know what you are doing you can disable this check using: + + git config hooks.allownonascii true +EOF + exit 1 +fi + +# Stop at any uncatched non-zero status +set -e + +# If there are whitespace errors, print the offending file names and fail. +git diff-index --check --cached $against -- + +# PHP checks +echo "Checking PHP syntax (linting)..." +git diff-index --diff-filter=ACMRT --cached --name-only HEAD -- | egrep '\.php$|\.inc$' | xargs --no-run-if-empty -d "\n" -n 1 php -l +echo "Checking PHP CodeStyle..." +git diff-index --diff-filter=ACMRT --cached --name-only HEAD -- | egrep '\.php$|\.inc$' | xargs --no-run-if-empty -d "\n" phpcs --standard=phpcs.xml --extensions=php --ignore=autoload.php --ignore=bootstrap/cache/ diff --git a/hooks-git/website-cracra/post-receive b/hooks-git/website-cracra/post-receive new file mode 100755 index 0000000..6b16416 --- /dev/null +++ b/hooks-git/website-cracra/post-receive @@ -0,0 +1,11 @@ +#!/bin/sh + +# Stop on the first error +set -ex + +export GIT_WORK_TREE=$GIT_DIR/.. + +# Theoretically, everything has been checked in the pre-receive hook +# and no local modification should go missing (at worst, there's the +# reflog) +git reset --hard diff --git a/hooks-git/website-cracra/pre-receive b/hooks-git/website-cracra/pre-receive new file mode 100755 index 0000000..339b2b0 --- /dev/null +++ b/hooks-git/website-cracra/pre-receive @@ -0,0 +1,14 @@ +#!/bin/sh + +# Stop on the first error +set -ex + +export GIT_WORK_TREE=$GIT_DIR/.. + +# Check for diff between the index and the staging area +git diff-index --quiet --cached HEAD -- +# Check for diff between the working tree and the staging area +git diff-files --quiet + +# No abandoned files +test -z "$( cd "$GIT_WORK_TREE" && GIT_WORK_TREE="$PWD" GIT_DIR="$GIT_WORK_TREE/.git" git --git-dir=.git ls-files --others )" diff --git a/hooks-git/website-cracra/readme.txt b/hooks-git/website-cracra/readme.txt new file mode 100644 index 0000000..fbb5b72 --- /dev/null +++ b/hooks-git/website-cracra/readme.txt @@ -0,0 +1,11 @@ +fr : Ces hooks permettent de mettre à jour un site web statique + directement via git push. + Il faut autoriser le "in place" dans le dépôt Git distant : + [receive] + denyCurrentBranch = ignore + +en : Those hooks allow to update a static website directly with + a git push. + You need to allow 'in place' in the remote git repository : + [receive] + denyCurrentBranch = ignore diff --git a/mini-ap-wifi/launch-wifi-ap-hostapd.conf b/mini-ap-wifi/launch-wifi-ap-hostapd.conf new file mode 100644 index 0000000..9a43694 --- /dev/null +++ b/mini-ap-wifi/launch-wifi-ap-hostapd.conf @@ -0,0 +1,1130 @@ +##### hostapd configuration file ############################################## +# Empty lines and lines starting with # are ignored + +# AP netdevice name (without 'ap' postfix, i.e., wlan0 uses wlan0ap for +# management frames); ath0 for madwifi +interface=wlan0 + +# In case of madwifi, atheros, and nl80211 driver interfaces, an additional +# configuration parameter, bridge, may be used to notify hostapd if the +# interface is included in a bridge. This parameter is not used with Host AP +# driver. If the bridge parameter is not set, the drivers will automatically +# figure out the bridge interface (assuming sysfs is enabled and mounted to +# /sys) and this parameter may not be needed. +# +# For nl80211, this parameter can be used to request the AP interface to be +# added to the bridge automatically (brctl may refuse to do this before hostapd +# has been started to change the interface mode). If needed, the bridge +# interface is also created. +#bridge=br0 + +# Driver interface type (hostap/wired/madwifi/test/none/nl80211/bsd); +# default: hostap). nl80211 is used with all Linux mac80211 drivers. +# Use driver=none if building hostapd as a standalone RADIUS server that does +# not control any wireless/wired driver. +# driver=hostap + +# hostapd event logger configuration +# +# Two output method: syslog and stdout (only usable if not forking to +# background). +# +# Module bitfield (ORed bitfield of modules that will be logged; -1 = all +# modules): +# bit 0 (1) = IEEE 802.11 +# bit 1 (2) = IEEE 802.1X +# bit 2 (4) = RADIUS +# bit 3 (8) = WPA +# bit 4 (16) = driver interface +# bit 5 (32) = IAPP +# bit 6 (64) = MLME +# +# Levels (minimum value for logged events): +# 0 = verbose debugging +# 1 = debugging +# 2 = informational messages +# 3 = notification +# 4 = warning +# +logger_syslog=-1 +logger_syslog_level=2 +logger_stdout=-1 +logger_stdout_level=2 + +# Dump file for state information (on SIGUSR1) +dump_file=/tmp/hostapd.dump + +# Interface for separate control program. If this is specified, hostapd +# will create this directory and a UNIX domain socket for listening to requests +# from external programs (CLI/GUI, etc.) for status information and +# configuration. The socket file will be named based on the interface name, so +# multiple hostapd processes/interfaces can be run at the same time if more +# than one interface is used. +# /var/run/hostapd is the recommended directory for sockets and by default, +# hostapd_cli will use it when trying to connect with hostapd. +ctrl_interface=/var/run/hostapd + +# Access control for the control interface can be configured by setting the +# directory to allow only members of a group to use sockets. This way, it is +# possible to run hostapd as root (since it needs to change network +# configuration and open raw sockets) and still allow GUI/CLI components to be +# run as non-root users. However, since the control interface can be used to +# change the network configuration, this access needs to be protected in many +# cases. By default, hostapd is configured to use gid 0 (root). If you +# want to allow non-root users to use the contron interface, add a new group +# and change this value to match with that group. Add users that should have +# control interface access to this group. +# +# This variable can be a group name or gid. +#ctrl_interface_group=wheel +ctrl_interface_group=0 + + +##### IEEE 802.11 related configuration ####################################### + +# SSID to be used in IEEE 802.11 management frames +ssid=MYNETWORK + +# Country code (ISO/IEC 3166-1). Used to set regulatory domain. +# Set as needed to indicate country in which device is operating. +# This can limit available channels and transmit power. +#country_code=US +country_code=FR + +# Enable IEEE 802.11d. This advertises the country_code and the set of allowed +# channels and transmit power levels based on the regulatory limits. The +# country_code setting must be configured with the correct country for +# IEEE 802.11d functions. +# (default: 0 = disabled) +#ieee80211d=1 + +# Operation mode (a = IEEE 802.11a, b = IEEE 802.11b, g = IEEE 802.11g, +# Default: IEEE 802.11b +hw_mode=g + +# Channel number (IEEE 802.11) +# (default: 0, i.e., not set) +# Please note that some drivers do not use this value from hostapd and the +# channel will need to be configured separately with iwconfig. +channel=11 + +# Beacon interval in kus (1.024 ms) (default: 100; range 15..65535) +beacon_int=100 + +# DTIM (delivery traffic information message) period (range 1..255): +# number of beacons between DTIMs (1 = every beacon includes DTIM element) +# (default: 2) +dtim_period=2 + +# Maximum number of stations allowed in station table. New stations will be +# rejected after the station table is full. IEEE 802.11 has a limit of 2007 +# different association IDs, so this number should not be larger than that. +# (default: 2007) +max_num_sta=255 + +# RTS/CTS threshold; 2347 = disabled (default); range 0..2347 +# If this field is not included in hostapd.conf, hostapd will not control +# RTS threshold and 'iwconfig wlan# rts ' can be used to set it. +rts_threshold=2347 + +# Fragmentation threshold; 2346 = disabled (default); range 256..2346 +# If this field is not included in hostapd.conf, hostapd will not control +# fragmentation threshold and 'iwconfig wlan# frag ' can be used to set +# it. +fragm_threshold=2346 + +# Rate configuration +# Default is to enable all rates supported by the hardware. This configuration +# item allows this list be filtered so that only the listed rates will be left +# in the list. If the list is empty, all rates are used. This list can have +# entries that are not in the list of rates the hardware supports (such entries +# are ignored). The entries in this list are in 100 kbps, i.e., 11 Mbps = 110. +# If this item is present, at least one rate have to be matching with the rates +# hardware supports. +# default: use the most common supported rate setting for the selected +# hw_mode (i.e., this line can be removed from configuration file in most +# cases) +#supported_rates=10 20 55 110 60 90 120 180 240 360 480 540 + +# Basic rate set configuration +# List of rates (in 100 kbps) that are included in the basic rate set. +# If this item is not included, usually reasonable default set is used. +#basic_rates=10 20 +#basic_rates=10 20 55 110 +#basic_rates=60 120 240 + +# Short Preamble +# This parameter can be used to enable optional use of short preamble for +# frames sent at 2 Mbps, 5.5 Mbps, and 11 Mbps to improve network performance. +# This applies only to IEEE 802.11b-compatible networks and this should only be +# enabled if the local hardware supports use of short preamble. If any of the +# associated STAs do not support short preamble, use of short preamble will be +# disabled (and enabled when such STAs disassociate) dynamically. +# 0 = do not allow use of short preamble (default) +# 1 = allow use of short preamble +#preamble=1 + +# Station MAC address -based authentication +# Please note that this kind of access control requires a driver that uses +# hostapd to take care of management frame processing and as such, this can be +# used with driver=hostap or driver=nl80211, but not with driver=madwifi. +# 0 = accept unless in deny list +# 1 = deny unless in accept list +# 2 = use external RADIUS server (accept/deny lists are searched first) +macaddr_acl=0 + +# Accept/deny lists are read from separate files (containing list of +# MAC addresses, one per line). Use absolute path name to make sure that the +# files can be read on SIGHUP configuration reloads. +#accept_mac_file=/etc/hostapd.accept +#deny_mac_file=/etc/hostapd.deny + +# IEEE 802.11 specifies two authentication algorithms. hostapd can be +# configured to allow both of these or only one. Open system authentication +# should be used with IEEE 802.1X. +# Bit fields of allowed authentication algorithms: +# bit 0 = Open System Authentication +# bit 1 = Shared Key Authentication (requires WEP) +auth_algs=3 + +# Send empty SSID in beacons and ignore probe request frames that do not +# specify full SSID, i.e., require stations to know SSID. +# default: disabled (0) +# 1 = send empty (length=0) SSID in beacon and ignore probe request for +# broadcast SSID +# 2 = clear SSID (ASCII 0), but keep the original length (this may be required +# with some clients that do not support empty SSID) and ignore probe +# requests for broadcast SSID +ignore_broadcast_ssid=0 + +# TX queue parameters (EDCF / bursting) +# tx_queue__ +# queues: data0, data1, data2, data3, after_beacon, beacon +# (data0 is the highest priority queue) +# parameters: +# aifs: AIFS (default 2) +# cwmin: cwMin (1, 3, 7, 15, 31, 63, 127, 255, 511, 1023) +# cwmax: cwMax (1, 3, 7, 15, 31, 63, 127, 255, 511, 1023); cwMax >= cwMin +# burst: maximum length (in milliseconds with precision of up to 0.1 ms) for +# bursting +# +# Default WMM parameters (IEEE 802.11 draft; 11-03-0504-03-000e): +# These parameters are used by the access point when transmitting frames +# to the clients. +# +# Low priority / AC_BK = background +#tx_queue_data3_aifs=7 +#tx_queue_data3_cwmin=15 +#tx_queue_data3_cwmax=1023 +#tx_queue_data3_burst=0 +# Note: for IEEE 802.11b mode: cWmin=31 cWmax=1023 burst=0 +# +# Normal priority / AC_BE = best effort +#tx_queue_data2_aifs=3 +#tx_queue_data2_cwmin=15 +#tx_queue_data2_cwmax=63 +#tx_queue_data2_burst=0 +# Note: for IEEE 802.11b mode: cWmin=31 cWmax=127 burst=0 +# +# High priority / AC_VI = video +#tx_queue_data1_aifs=1 +#tx_queue_data1_cwmin=7 +#tx_queue_data1_cwmax=15 +#tx_queue_data1_burst=3.0 +# Note: for IEEE 802.11b mode: cWmin=15 cWmax=31 burst=6.0 +# +# Highest priority / AC_VO = voice +#tx_queue_data0_aifs=1 +#tx_queue_data0_cwmin=3 +#tx_queue_data0_cwmax=7 +#tx_queue_data0_burst=1.5 +# Note: for IEEE 802.11b mode: cWmin=7 cWmax=15 burst=3.3 + +# 802.1D Tag (= UP) to AC mappings +# WMM specifies following mapping of data frames to different ACs. This mapping +# can be configured using Linux QoS/tc and sch_pktpri.o module. +# 802.1D Tag 802.1D Designation Access Category WMM Designation +# 1 BK AC_BK Background +# 2 - AC_BK Background +# 0 BE AC_BE Best Effort +# 3 EE AC_BE Best Effort +# 4 CL AC_VI Video +# 5 VI AC_VI Video +# 6 VO AC_VO Voice +# 7 NC AC_VO Voice +# Data frames with no priority information: AC_BE +# Management frames: AC_VO +# PS-Poll frames: AC_BE + +# Default WMM parameters (IEEE 802.11 draft; 11-03-0504-03-000e): +# for 802.11a or 802.11g networks +# These parameters are sent to WMM clients when they associate. +# The parameters will be used by WMM clients for frames transmitted to the +# access point. +# +# note - txop_limit is in units of 32microseconds +# note - acm is admission control mandatory flag. 0 = admission control not +# required, 1 = mandatory +# note - here cwMin and cmMax are in exponent form. the actual cw value used +# will be (2^n)-1 where n is the value given here +# +wmm_enabled=1 +# +# WMM-PS Unscheduled Automatic Power Save Delivery [U-APSD] +# Enable this flag if U-APSD supported outside hostapd (eg., Firmware/driver) +#uapsd_advertisement_enabled=1 +# +# Low priority / AC_BK = background +wmm_ac_bk_cwmin=4 +wmm_ac_bk_cwmax=10 +wmm_ac_bk_aifs=7 +wmm_ac_bk_txop_limit=0 +wmm_ac_bk_acm=0 +# Note: for IEEE 802.11b mode: cWmin=5 cWmax=10 +# +# Normal priority / AC_BE = best effort +wmm_ac_be_aifs=3 +wmm_ac_be_cwmin=4 +wmm_ac_be_cwmax=10 +wmm_ac_be_txop_limit=0 +wmm_ac_be_acm=0 +# Note: for IEEE 802.11b mode: cWmin=5 cWmax=7 +# +# High priority / AC_VI = video +wmm_ac_vi_aifs=2 +wmm_ac_vi_cwmin=3 +wmm_ac_vi_cwmax=4 +wmm_ac_vi_txop_limit=94 +wmm_ac_vi_acm=0 +# Note: for IEEE 802.11b mode: cWmin=4 cWmax=5 txop_limit=188 +# +# Highest priority / AC_VO = voice +wmm_ac_vo_aifs=2 +wmm_ac_vo_cwmin=2 +wmm_ac_vo_cwmax=3 +wmm_ac_vo_txop_limit=47 +wmm_ac_vo_acm=0 +# Note: for IEEE 802.11b mode: cWmin=3 cWmax=4 burst=102 + +# Static WEP key configuration +# +# The key number to use when transmitting. +# It must be between 0 and 3, and the corresponding key must be set. +# default: not set +#wep_default_key=0 +# The WEP keys to use. +# A key may be a quoted string or unquoted hexadecimal digits. +# The key length should be 5, 13, or 16 characters, or 10, 26, or 32 +# digits, depending on whether 40-bit (64-bit), 104-bit (128-bit), or +# 128-bit (152-bit) WEP is used. +# Only the default key must be supplied; the others are optional. +# default: not set +#wep_key0=123456789a +#wep_key1="vwxyz" +#wep_key2=0102030405060708090a0b0c0d +#wep_key3=".2.4.6.8.0.23" + +# Station inactivity limit +# +# If a station does not send anything in ap_max_inactivity seconds, an +# empty data frame is sent to it in order to verify whether it is +# still in range. If this frame is not ACKed, the station will be +# disassociated and then deauthenticated. This feature is used to +# clear station table of old entries when the STAs move out of the +# range. +# +# The station can associate again with the AP if it is still in range; +# this inactivity poll is just used as a nicer way of verifying +# inactivity; i.e., client will not report broken connection because +# disassociation frame is not sent immediately without first polling +# the STA with a data frame. +# default: 300 (i.e., 5 minutes) +#ap_max_inactivity=300 + +# Disassociate stations based on excessive transmission failures or other +# indications of connection loss. This depends on the driver capabilities and +# may not be available with all drivers. +#disassoc_low_ack=1 + +# Maximum allowed Listen Interval (how many Beacon periods STAs are allowed to +# remain asleep). Default: 65535 (no limit apart from field size) +#max_listen_interval=100 + +# WDS (4-address frame) mode with per-station virtual interfaces +# (only supported with driver=nl80211) +# This mode allows associated stations to use 4-address frames to allow layer 2 +# bridging to be used. +#wds_sta=1 + +# If bridge parameter is set, the WDS STA interface will be added to the same +# bridge by default. This can be overridden with the wds_bridge parameter to +# use a separate bridge. +#wds_bridge=wds-br0 + +# Client isolation can be used to prevent low-level bridging of frames between +# associated stations in the BSS. By default, this bridging is allowed. +#ap_isolate=1 + +##### IEEE 802.11n related configuration ###################################### + +# ieee80211n: Whether IEEE 802.11n (HT) is enabled +# 0 = disabled (default) +# 1 = enabled +# Note: You will also need to enable WMM for full HT functionality. +#ieee80211n=1 + +# ht_capab: HT capabilities (list of flags) +# LDPC coding capability: [LDPC] = supported +# Supported channel width set: [HT40-] = both 20 MHz and 40 MHz with secondary +# channel below the primary channel; [HT40+] = both 20 MHz and 40 MHz +# with secondary channel below the primary channel +# (20 MHz only if neither is set) +# Note: There are limits on which channels can be used with HT40- and +# HT40+. Following table shows the channels that may be available for +# HT40- and HT40+ use per IEEE 802.11n Annex J: +# freq HT40- HT40+ +# 2.4 GHz 5-13 1-7 (1-9 in Europe/Japan) +# 5 GHz 40,48,56,64 36,44,52,60 +# (depending on the location, not all of these channels may be available +# for use) +# Please note that 40 MHz channels may switch their primary and secondary +# channels if needed or creation of 40 MHz channel maybe rejected based +# on overlapping BSSes. These changes are done automatically when hostapd +# is setting up the 40 MHz channel. +# Spatial Multiplexing (SM) Power Save: [SMPS-STATIC] or [SMPS-DYNAMIC] +# (SMPS disabled if neither is set) +# HT-greenfield: [GF] (disabled if not set) +# Short GI for 20 MHz: [SHORT-GI-20] (disabled if not set) +# Short GI for 40 MHz: [SHORT-GI-40] (disabled if not set) +# Tx STBC: [TX-STBC] (disabled if not set) +# Rx STBC: [RX-STBC1] (one spatial stream), [RX-STBC12] (one or two spatial +# streams), or [RX-STBC123] (one, two, or three spatial streams); Rx STBC +# disabled if none of these set +# HT-delayed Block Ack: [DELAYED-BA] (disabled if not set) +# Maximum A-MSDU length: [MAX-AMSDU-7935] for 7935 octets (3839 octets if not +# set) +# DSSS/CCK Mode in 40 MHz: [DSSS_CCK-40] = allowed (not allowed if not set) +# PSMP support: [PSMP] (disabled if not set) +# L-SIG TXOP protection support: [LSIG-TXOP-PROT] (disabled if not set) +#ht_capab=[HT40-][SHORT-GI-20][SHORT-GI-40] + +# Require stations to support HT PHY (reject association if they do not) +#require_ht=1 + +##### IEEE 802.1X-2004 related configuration ################################## + +# Require IEEE 802.1X authorization +#ieee8021x=1 + +# IEEE 802.1X/EAPOL version +# hostapd is implemented based on IEEE Std 802.1X-2004 which defines EAPOL +# version 2. However, there are many client implementations that do not handle +# the new version number correctly (they seem to drop the frames completely). +# In order to make hostapd interoperate with these clients, the version number +# can be set to the older version (1) with this configuration value. +#eapol_version=2 + +# Optional displayable message sent with EAP Request-Identity. The first \0 +# in this string will be converted to ASCII-0 (nul). This can be used to +# separate network info (comma separated list of attribute=value pairs); see, +# e.g., RFC 4284. +#eap_message=hello +#eap_message=hello\0networkid=netw,nasid=foo,portid=0,NAIRealms=example.com + +# WEP rekeying (disabled if key lengths are not set or are set to 0) +# Key lengths for default/broadcast and individual/unicast keys: +# 5 = 40-bit WEP (also known as 64-bit WEP with 40 secret bits) +# 13 = 104-bit WEP (also known as 128-bit WEP with 104 secret bits) +#wep_key_len_broadcast=5 +#wep_key_len_unicast=5 +# Rekeying period in seconds. 0 = do not rekey (i.e., set keys only once) +#wep_rekey_period=300 + +# EAPOL-Key index workaround (set bit7) for WinXP Supplicant (needed only if +# only broadcast keys are used) +eapol_key_index_workaround=0 + +# EAP reauthentication period in seconds (default: 3600 seconds; 0 = disable +# reauthentication). +#eap_reauth_period=3600 + +# Use PAE group address (01:80:c2:00:00:03) instead of individual target +# address when sending EAPOL frames with driver=wired. This is the most common +# mechanism used in wired authentication, but it also requires that the port +# is only used by one station. +#use_pae_group_addr=1 + +##### Integrated EAP server ################################################### + +# Optionally, hostapd can be configured to use an integrated EAP server +# to process EAP authentication locally without need for an external RADIUS +# server. This functionality can be used both as a local authentication server +# for IEEE 802.1X/EAPOL and as a RADIUS server for other devices. + +# Use integrated EAP server instead of external RADIUS authentication +# server. This is also needed if hostapd is configured to act as a RADIUS +# authentication server. +eap_server=0 + +# Path for EAP server user database +#eap_user_file=/etc/hostapd.eap_user + +# CA certificate (PEM or DER file) for EAP-TLS/PEAP/TTLS +#ca_cert=/etc/hostapd.ca.pem + +# Server certificate (PEM or DER file) for EAP-TLS/PEAP/TTLS +#server_cert=/etc/hostapd.server.pem + +# Private key matching with the server certificate for EAP-TLS/PEAP/TTLS +# This may point to the same file as server_cert if both certificate and key +# are included in a single file. PKCS#12 (PFX) file (.p12/.pfx) can also be +# used by commenting out server_cert and specifying the PFX file as the +# private_key. +#private_key=/etc/hostapd.server.prv + +# Passphrase for private key +#private_key_passwd=secret passphrase + +# Enable CRL verification. +# Note: hostapd does not yet support CRL downloading based on CDP. Thus, a +# valid CRL signed by the CA is required to be included in the ca_cert file. +# This can be done by using PEM format for CA certificate and CRL and +# concatenating these into one file. Whenever CRL changes, hostapd needs to be +# restarted to take the new CRL into use. +# 0 = do not verify CRLs (default) +# 1 = check the CRL of the user certificate +# 2 = check all CRLs in the certificate path +#check_crl=1 + +# dh_file: File path to DH/DSA parameters file (in PEM format) +# This is an optional configuration file for setting parameters for an +# ephemeral DH key exchange. In most cases, the default RSA authentication does +# not use this configuration. However, it is possible setup RSA to use +# ephemeral DH key exchange. In addition, ciphers with DSA keys always use +# ephemeral DH keys. This can be used to achieve forward secrecy. If the file +# is in DSA parameters format, it will be automatically converted into DH +# params. This parameter is required if anonymous EAP-FAST is used. +# You can generate DH parameters file with OpenSSL, e.g., +# "openssl dhparam -out /etc/hostapd.dh.pem 1024" +#dh_file=/etc/hostapd.dh.pem + +# Fragment size for EAP methods +#fragment_size=1400 + +# Configuration data for EAP-SIM database/authentication gateway interface. +# This is a text string in implementation specific format. The example +# implementation in eap_sim_db.c uses this as the UNIX domain socket name for +# the HLR/AuC gateway (e.g., hlr_auc_gw). In this case, the path uses "unix:" +# prefix. +#eap_sim_db=unix:/tmp/hlr_auc_gw.sock + +# Encryption key for EAP-FAST PAC-Opaque values. This key must be a secret, +# random value. It is configured as a 16-octet value in hex format. It can be +# generated, e.g., with the following command: +# od -tx1 -v -N16 /dev/random | colrm 1 8 | tr -d ' ' +#pac_opaque_encr_key=000102030405060708090a0b0c0d0e0f + +# EAP-FAST authority identity (A-ID) +# A-ID indicates the identity of the authority that issues PACs. The A-ID +# should be unique across all issuing servers. In theory, this is a variable +# length field, but due to some existing implementations requiring A-ID to be +# 16 octets in length, it is strongly recommended to use that length for the +# field to provid interoperability with deployed peer implementations. This +# field is configured in hex format. +#eap_fast_a_id=101112131415161718191a1b1c1d1e1f + +# EAP-FAST authority identifier information (A-ID-Info) +# This is a user-friendly name for the A-ID. For example, the enterprise name +# and server name in a human-readable format. This field is encoded as UTF-8. +#eap_fast_a_id_info=test server + +# Enable/disable different EAP-FAST provisioning modes: +#0 = provisioning disabled +#1 = only anonymous provisioning allowed +#2 = only authenticated provisioning allowed +#3 = both provisioning modes allowed (default) +#eap_fast_prov=3 + +# EAP-FAST PAC-Key lifetime in seconds (hard limit) +#pac_key_lifetime=604800 + +# EAP-FAST PAC-Key refresh time in seconds (soft limit on remaining hard +# limit). The server will generate a new PAC-Key when this number of seconds +# (or fewer) of the lifetime remains. +#pac_key_refresh_time=86400 + +# EAP-SIM and EAP-AKA protected success/failure indication using AT_RESULT_IND +# (default: 0 = disabled). +#eap_sim_aka_result_ind=1 + +# Trusted Network Connect (TNC) +# If enabled, TNC validation will be required before the peer is allowed to +# connect. Note: This is only used with EAP-TTLS and EAP-FAST. If any other +# EAP method is enabled, the peer will be allowed to connect without TNC. +#tnc=1 + + +##### IEEE 802.11f - Inter-Access Point Protocol (IAPP) ####################### + +# Interface to be used for IAPP broadcast packets +#iapp_interface=eth0 + + +##### RADIUS client configuration ############################################# +# for IEEE 802.1X with external Authentication Server, IEEE 802.11 +# authentication with external ACL for MAC addresses, and accounting + +# The own IP address of the access point (used as NAS-IP-Address) +own_ip_addr=127.0.0.1 + +# Optional NAS-Identifier string for RADIUS messages. When used, this should be +# a unique to the NAS within the scope of the RADIUS server. For example, a +# fully qualified domain name can be used here. +# When using IEEE 802.11r, nas_identifier must be set and must be between 1 and +# 48 octets long. +#nas_identifier=ap.example.com + +# RADIUS authentication server +#auth_server_addr=127.0.0.1 +#auth_server_port=1812 +#auth_server_shared_secret=secret + +# RADIUS accounting server +#acct_server_addr=127.0.0.1 +#acct_server_port=1813 +#acct_server_shared_secret=secret + +# Secondary RADIUS servers; to be used if primary one does not reply to +# RADIUS packets. These are optional and there can be more than one secondary +# server listed. +#auth_server_addr=127.0.0.2 +#auth_server_port=1812 +#auth_server_shared_secret=secret2 +# +#acct_server_addr=127.0.0.2 +#acct_server_port=1813 +#acct_server_shared_secret=secret2 + +# Retry interval for trying to return to the primary RADIUS server (in +# seconds). RADIUS client code will automatically try to use the next server +# when the current server is not replying to requests. If this interval is set, +# primary server will be retried after configured amount of time even if the +# currently used secondary server is still working. +#radius_retry_primary_interval=600 + + +# Interim accounting update interval +# If this is set (larger than 0) and acct_server is configured, hostapd will +# send interim accounting updates every N seconds. Note: if set, this overrides +# possible Acct-Interim-Interval attribute in Access-Accept message. Thus, this +# value should not be configured in hostapd.conf, if RADIUS server is used to +# control the interim interval. +# This value should not be less 600 (10 minutes) and must not be less than +# 60 (1 minute). +#radius_acct_interim_interval=600 + +# Dynamic VLAN mode; allow RADIUS authentication server to decide which VLAN +# is used for the stations. This information is parsed from following RADIUS +# attributes based on RFC 3580 and RFC 2868: Tunnel-Type (value 13 = VLAN), +# Tunnel-Medium-Type (value 6 = IEEE 802), Tunnel-Private-Group-ID (value +# VLANID as a string). vlan_file option below must be configured if dynamic +# VLANs are used. Optionally, the local MAC ACL list (accept_mac_file) can be +# used to set static client MAC address to VLAN ID mapping. +# 0 = disabled (default) +# 1 = option; use default interface if RADIUS server does not include VLAN ID +# 2 = required; reject authentication if RADIUS server does not include VLAN ID +#dynamic_vlan=0 + +# VLAN interface list for dynamic VLAN mode is read from a separate text file. +# This list is used to map VLAN ID from the RADIUS server to a network +# interface. Each station is bound to one interface in the same way as with +# multiple BSSIDs or SSIDs. Each line in this text file is defining a new +# interface and the line must include VLAN ID and interface name separated by +# white space (space or tab). +#vlan_file=/etc/hostapd.vlan + +# Interface where 802.1q tagged packets should appear when a RADIUS server is +# used to determine which VLAN a station is on. hostapd creates a bridge for +# each VLAN. Then hostapd adds a VLAN interface (associated with the interface +# indicated by 'vlan_tagged_interface') and the appropriate wireless interface +# to the bridge. +#vlan_tagged_interface=eth0 + + +##### RADIUS authentication server configuration ############################## + +# hostapd can be used as a RADIUS authentication server for other hosts. This +# requires that the integrated EAP server is also enabled and both +# authentication services are sharing the same configuration. + +# File name of the RADIUS clients configuration for the RADIUS server. If this +# commented out, RADIUS server is disabled. +#radius_server_clients=/etc/hostapd.radius_clients + +# The UDP port number for the RADIUS authentication server +#radius_server_auth_port=1812 + +# Use IPv6 with RADIUS server (IPv4 will also be supported using IPv6 API) +#radius_server_ipv6=1 + + +##### WPA/IEEE 802.11i configuration ########################################## + +# Enable WPA. Setting this variable configures the AP to require WPA (either +# WPA-PSK or WPA-RADIUS/EAP based on other configuration). For WPA-PSK, either +# wpa_psk or wpa_passphrase must be set and wpa_key_mgmt must include WPA-PSK. +# For WPA-RADIUS/EAP, ieee8021x must be set (but without dynamic WEP keys), +# RADIUS authentication server must be configured, and WPA-EAP must be included +# in wpa_key_mgmt. +# This field is a bit field that can be used to enable WPA (IEEE 802.11i/D3.0) +# and/or WPA2 (full IEEE 802.11i/RSN): +# bit0 = WPA +# bit1 = IEEE 802.11i/RSN (WPA2) (dot11RSNAEnabled) +wpa=1 + +# WPA pre-shared keys for WPA-PSK. This can be either entered as a 256-bit +# secret in hex format (64 hex digits), wpa_psk, or as an ASCII passphrase +# (8..63 characters) that will be converted to PSK. This conversion uses SSID +# so the PSK changes when ASCII passphrase is used and the SSID is changed. +# wpa_psk (dot11RSNAConfigPSKValue) +# wpa_passphrase (dot11RSNAConfigPSKPassPhrase) +#wpa_psk=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef +#wpa_passphrase=secret passphrase +wpa_passphrase=MYPASSWORD + +# Optionally, WPA PSKs can be read from a separate text file (containing list +# of (PSK,MAC address) pairs. This allows more than one PSK to be configured. +# Use absolute path name to make sure that the files can be read on SIGHUP +# configuration reloads. +#wpa_psk_file=/etc/hostapd.wpa_psk + +# Set of accepted key management algorithms (WPA-PSK, WPA-EAP, or both). The +# entries are separated with a space. WPA-PSK-SHA256 and WPA-EAP-SHA256 can be +# added to enable SHA256-based stronger algorithms. +# (dot11RSNAConfigAuthenticationSuitesTable) +#wpa_key_mgmt=WPA-PSK WPA-EAP +wpa_key_mgmt=WPA-PSK + +# Set of accepted cipher suites (encryption algorithms) for pairwise keys +# (unicast packets). This is a space separated list of algorithms: +# CCMP = AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0] +# TKIP = Temporal Key Integrity Protocol [IEEE 802.11i/D7.0] +# Group cipher suite (encryption algorithm for broadcast and multicast frames) +# is automatically selected based on this configuration. If only CCMP is +# allowed as the pairwise cipher, group cipher will also be CCMP. Otherwise, +# TKIP will be used as the group cipher. +# (dot11RSNAConfigPairwiseCiphersTable) +# Pairwise cipher for WPA (v1) (default: TKIP) +#wpa_pairwise=TKIP CCMP +# Pairwise cipher for RSN/WPA2 (default: use wpa_pairwise value) +#rsn_pairwise=CCMP + +# Time interval for rekeying GTK (broadcast/multicast encryption keys) in +# seconds. (dot11RSNAConfigGroupRekeyTime) +#wpa_group_rekey=600 + +# Rekey GTK when any STA that possesses the current GTK is leaving the BSS. +# (dot11RSNAConfigGroupRekeyStrict) +#wpa_strict_rekey=1 + +# Time interval for rekeying GMK (master key used internally to generate GTKs +# (in seconds). +#wpa_gmk_rekey=86400 + +# Maximum lifetime for PTK in seconds. This can be used to enforce rekeying of +# PTK to mitigate some attacks against TKIP deficiencies. +#wpa_ptk_rekey=600 + +# Enable IEEE 802.11i/RSN/WPA2 pre-authentication. This is used to speed up +# roaming be pre-authenticating IEEE 802.1X/EAP part of the full RSN +# authentication and key handshake before actually associating with a new AP. +# (dot11RSNAPreauthenticationEnabled) +#rsn_preauth=1 +# +# Space separated list of interfaces from which pre-authentication frames are +# accepted (e.g., 'eth0' or 'eth0 wlan0wds0'. This list should include all +# interface that are used for connections to other APs. This could include +# wired interfaces and WDS links. The normal wireless data interface towards +# associated stations (e.g., wlan0) should not be added, since +# pre-authentication is only used with APs other than the currently associated +# one. +#rsn_preauth_interfaces=eth0 + +# peerkey: Whether PeerKey negotiation for direct links (IEEE 802.11e) is +# allowed. This is only used with RSN/WPA2. +# 0 = disabled (default) +# 1 = enabled +#peerkey=1 + +# ieee80211w: Whether management frame protection (MFP) is enabled +# 0 = disabled (default) +# 1 = optional +# 2 = required +#ieee80211w=0 + +# Association SA Query maximum timeout (in TU = 1.024 ms; for MFP) +# (maximum time to wait for a SA Query response) +# dot11AssociationSAQueryMaximumTimeout, 1...4294967295 +#assoc_sa_query_max_timeout=1000 + +# Association SA Query retry timeout (in TU = 1.024 ms; for MFP) +# (time between two subsequent SA Query requests) +# dot11AssociationSAQueryRetryTimeout, 1...4294967295 +#assoc_sa_query_retry_timeout=201 + +# disable_pmksa_caching: Disable PMKSA caching +# This parameter can be used to disable caching of PMKSA created through EAP +# authentication. RSN preauthentication may still end up using PMKSA caching if +# it is enabled (rsn_preauth=1). +# 0 = PMKSA caching enabled (default) +# 1 = PMKSA caching disabled +#disable_pmksa_caching=0 + +# okc: Opportunistic Key Caching (aka Proactive Key Caching) +# Allow PMK cache to be shared opportunistically among configured interfaces +# and BSSes (i.e., all configurations within a single hostapd process). +# 0 = disabled (default) +# 1 = enabled +#okc=1 + + +##### IEEE 802.11r configuration ############################################## + +# Mobility Domain identifier (dot11FTMobilityDomainID, MDID) +# MDID is used to indicate a group of APs (within an ESS, i.e., sharing the +# same SSID) between which a STA can use Fast BSS Transition. +# 2-octet identifier as a hex string. +#mobility_domain=a1b2 + +# PMK-R0 Key Holder identifier (dot11FTR0KeyHolderID) +# 1 to 48 octet identifier. +# This is configured with nas_identifier (see RADIUS client section above). + +# Default lifetime of the PMK-RO in minutes; range 1..65535 +# (dot11FTR0KeyLifetime) +#r0_key_lifetime=10000 + +# PMK-R1 Key Holder identifier (dot11FTR1KeyHolderID) +# 6-octet identifier as a hex string. +#r1_key_holder=000102030405 + +# Reassociation deadline in time units (TUs / 1.024 ms; range 1000..65535) +# (dot11FTReassociationDeadline) +#reassociation_deadline=1000 + +# List of R0KHs in the same Mobility Domain +# format: <128-bit key as hex string> +# This list is used to map R0KH-ID (NAS Identifier) to a destination MAC +# address when requesting PMK-R1 key from the R0KH that the STA used during the +# Initial Mobility Domain Association. +#r0kh=02:01:02:03:04:05 r0kh-1.example.com 000102030405060708090a0b0c0d0e0f +#r0kh=02:01:02:03:04:06 r0kh-2.example.com 00112233445566778899aabbccddeeff +# And so on.. One line per R0KH. + +# List of R1KHs in the same Mobility Domain +# format: <128-bit key as hex string> +# This list is used to map R1KH-ID to a destination MAC address when sending +# PMK-R1 key from the R0KH. This is also the list of authorized R1KHs in the MD +# that can request PMK-R1 keys. +#r1kh=02:01:02:03:04:05 02:11:22:33:44:55 000102030405060708090a0b0c0d0e0f +#r1kh=02:01:02:03:04:06 02:11:22:33:44:66 00112233445566778899aabbccddeeff +# And so on.. One line per R1KH. + +# Whether PMK-R1 push is enabled at R0KH +# 0 = do not push PMK-R1 to all configured R1KHs (default) +# 1 = push PMK-R1 to all configured R1KHs whenever a new PMK-R0 is derived +#pmk_r1_push=1 + +##### Neighbor table ########################################################## +# Maximum number of entries kept in AP table (either for neigbor table or for +# detecting Overlapping Legacy BSS Condition). The oldest entry will be +# removed when adding a new entry that would make the list grow over this +# limit. Note! WFA certification for IEEE 802.11g requires that OLBC is +# enabled, so this field should not be set to 0 when using IEEE 802.11g. +# default: 255 +#ap_table_max_size=255 + +# Number of seconds of no frames received after which entries may be deleted +# from the AP table. Since passive scanning is not usually performed frequently +# this should not be set to very small value. In addition, there is no +# guarantee that every scan cycle will receive beacon frames from the +# neighboring APs. +# default: 60 +#ap_table_expiration_time=3600 + + +##### Wi-Fi Protected Setup (WPS) ############################################# + +# WPS state +# 0 = WPS disabled (default) +# 1 = WPS enabled, not configured +# 2 = WPS enabled, configured +#wps_state=2 + +# AP can be configured into a locked state where new WPS Registrar are not +# accepted, but previously authorized Registrars (including the internal one) +# can continue to add new Enrollees. +#ap_setup_locked=1 + +# Universally Unique IDentifier (UUID; see RFC 4122) of the device +# This value is used as the UUID for the internal WPS Registrar. If the AP +# is also using UPnP, this value should be set to the device's UPnP UUID. +# If not configured, UUID will be generated based on the local MAC address. +#uuid=12345678-9abc-def0-1234-56789abcdef0 + +# Note: If wpa_psk_file is set, WPS is used to generate random, per-device PSKs +# that will be appended to the wpa_psk_file. If wpa_psk_file is not set, the +# default PSK (wpa_psk/wpa_passphrase) will be delivered to Enrollees. Use of +# per-device PSKs is recommended as the more secure option (i.e., make sure to +# set wpa_psk_file when using WPS with WPA-PSK). + +# When an Enrollee requests access to the network with PIN method, the Enrollee +# PIN will need to be entered for the Registrar. PIN request notifications are +# sent to hostapd ctrl_iface monitor. In addition, they can be written to a +# text file that could be used, e.g., to populate the AP administration UI with +# pending PIN requests. If the following variable is set, the PIN requests will +# be written to the configured file. +#wps_pin_requests=/var/run/hostapd_wps_pin_requests + +# Device Name +# User-friendly description of device; up to 32 octets encoded in UTF-8 +#device_name=Wireless AP + +# Manufacturer +# The manufacturer of the device (up to 64 ASCII characters) +#manufacturer=Company + +# Model Name +# Model of the device (up to 32 ASCII characters) +#model_name=WAP + +# Model Number +# Additional device description (up to 32 ASCII characters) +#model_number=123 + +# Serial Number +# Serial number of the device (up to 32 characters) +#serial_number=12345 + +# Primary Device Type +# Used format: -- +# categ = Category as an integer value +# OUI = OUI and type octet as a 4-octet hex-encoded value; 0050F204 for +# default WPS OUI +# subcateg = OUI-specific Sub Category as an integer value +# Examples: +# 1-0050F204-1 (Computer / PC) +# 1-0050F204-2 (Computer / Server) +# 5-0050F204-1 (Storage / NAS) +# 6-0050F204-1 (Network Infrastructure / AP) +#device_type=6-0050F204-1 + +# OS Version +# 4-octet operating system version number (hex string) +#os_version=01020300 + +# Config Methods +# List of the supported configuration methods +# Available methods: usba ethernet label display ext_nfc_token int_nfc_token +# nfc_interface push_button keypad virtual_display physical_display +# virtual_push_button physical_push_button +#config_methods=label virtual_display virtual_push_button keypad + +# WPS capability discovery workaround for PBC with Windows 7 +# Windows 7 uses incorrect way of figuring out AP's WPS capabilities by acting +# as a Registrar and using M1 from the AP. The config methods attribute in that +# message is supposed to indicate only the configuration method supported by +# the AP in Enrollee role, i.e., to add an external Registrar. For that case, +# PBC shall not be used and as such, the PushButton config method is removed +# from M1 by default. If pbc_in_m1=1 is included in the configuration file, +# the PushButton config method is left in M1 (if included in config_methods +# parameter) to allow Windows 7 to use PBC instead of PIN (e.g., from a label +# in the AP). +#pbc_in_m1=1 + +# Static access point PIN for initial configuration and adding Registrars +# If not set, hostapd will not allow external WPS Registrars to control the +# access point. The AP PIN can also be set at runtime with hostapd_cli +# wps_ap_pin command. Use of temporary (enabled by user action) and random +# AP PIN is much more secure than configuring a static AP PIN here. As such, +# use of the ap_pin parameter is not recommended if the AP device has means for +# displaying a random PIN. +#ap_pin=12345670 + +# Skip building of automatic WPS credential +# This can be used to allow the automatically generated Credential attribute to +# be replaced with pre-configured Credential(s). +#skip_cred_build=1 + +# Additional Credential attribute(s) +# This option can be used to add pre-configured Credential attributes into M8 +# message when acting as a Registrar. If skip_cred_build=1, this data will also +# be able to override the Credential attribute that would have otherwise been +# automatically generated based on network configuration. This configuration +# option points to an external file that much contain the WPS Credential +# attribute(s) as binary data. +#extra_cred=hostapd.cred + +# Credential processing +# 0 = process received credentials internally (default) +# 1 = do not process received credentials; just pass them over ctrl_iface to +# external program(s) +# 2 = process received credentials internally and pass them over ctrl_iface +# to external program(s) +# Note: With wps_cred_processing=1, skip_cred_build should be set to 1 and +# extra_cred be used to provide the Credential data for Enrollees. +# +# wps_cred_processing=1 will disabled automatic updates of hostapd.conf file +# both for Credential processing and for marking AP Setup Locked based on +# validation failures of AP PIN. An external program is responsible on updating +# the configuration appropriately in this case. +#wps_cred_processing=0 + +# AP Settings Attributes for M7 +# By default, hostapd generates the AP Settings Attributes for M7 based on the +# current configuration. It is possible to override this by providing a file +# with pre-configured attributes. This is similar to extra_cred file format, +# but the AP Settings attributes are not encapsulated in a Credential +# attribute. +#ap_settings=hostapd.ap_settings + +# WPS UPnP interface +# If set, support for external Registrars is enabled. +#upnp_iface=br0 + +# Friendly Name (required for UPnP) +# Short description for end use. Should be less than 64 characters. +#friendly_name=WPS Access Point + +# Manufacturer URL (optional for UPnP) +#manufacturer_url=http://www.example.com/ + +# Model Description (recommended for UPnP) +# Long description for end user. Should be less than 128 characters. +#model_description=Wireless Access Point + +# Model URL (optional for UPnP) +#model_url=http://www.example.com/model/ + +# Universal Product Code (optional for UPnP) +# 12-digit, all-numeric code that identifies the consumer package. +#upc=123456789012 + +##### Wi-Fi Direct (P2P) ###################################################### + +# Enable P2P Device management +#manage_p2p=1 + +# Allow cross connection +#allow_cross_connection=1 + +#### TDLS (IEEE 802.11z-2010) ################################################# + +# Prohibit use of TDLS in this BSS +#tdls_prohibit=1 + +# Prohibit use of TDLS Channel Switching in this BSS +#tdls_prohibit_chan_switch=1 + +##### IEEE 802.11v-2011 ####################################################### + +# Time advertisement +# 0 = disabled (default) +# 2 = UTC time at which the TSF timer is 0 +#time_advertisement=2 + +# Local time zone as specified in 8.3 of IEEE Std 1003.1-2004: +# stdoffset[dst[offset][,start[/time],end[/time]]] +#time_zone=EST5 + +##### IEEE 802.11u-2011 ####################################################### + +# Enable Interworking service +#interworking=1 + +# Access Network Type +# 0 = Private network +# 1 = Private network with guest access +# 2 = Chargeable public network +# 3 = Free public network +# 4 = Personal device network +# 5 = Emergency services only network +# 14 = Test or experimental +# 15 = Wildcard +#access_network_type=0 + +# Whether the network provides connectivity to the Internet +# 0 = Unspecified +# 1 = Network provides connectivity to the Internet +#internet=1 + +# Additional Step Required for Access +# Note: This is only used with open network, i.e., ASRA shall ne set to 0 if +# RSN is used. +#asra=0 + +# Emergency services reachable +#esr=0 + +# Unauthenticated emergency service accessible +#uesa=0 + +# Venue Info (optional) +# The available values are defined in IEEE Std 802.11u-2011, 7.3.1.34. +# Example values (group,type): +# 0,0 = Unspecified +# 1,7 = Convention Center +# 1,13 = Coffee Shop +# 2,0 = Unspecified Business +# 7,1 Private Residence +#venue_group=7 +#venue_type=1 + +# Homogeneous ESS identifier (optional; dot11HESSID) +# If set, this shall be identifical to one of the BSSIDs in the homogeneous +# ESS and this shall be set to the same value across all BSSs in homogeneous +# ESS. +#hessid=02:03:04:05:06:07 + +# Roaming Consortium List +# Arbitrary number of Roaming Consortium OIs can be configured with each line +# adding a new OI to the list. The first three entries are available through +# Beacon and Probe Response frames. Any additional entry will be available only +# through ANQP queries. Each OI is between 3 and 15 octets and is configured a +# a hexstring. +#roaming_consortium=021122 +#roaming_consortium=2233445566 + +##### Multiple BSSID support ################################################## +# +# Above configuration is using the default interface (wlan#, or multi-SSID VLAN +# interfaces). Other BSSIDs can be added by using separator 'bss' with +# default interface name to be allocated for the data packets of the new BSS. +# +# hostapd will generate BSSID mask based on the BSSIDs that are +# configured. hostapd will verify that dev_addr & MASK == dev_addr. If this is +# not the case, the MAC address of the radio must be changed before starting +# hostapd (ifconfig wlan0 hw ether ). If a BSSID is configured for +# every secondary BSS, this limitation is not applied at hostapd and other +# masks may be used if the driver supports them (e.g., swap the locally +# administered bit) +# +# BSSIDs are assigned in order to each BSS, unless an explicit BSSID is +# specified using the 'bssid' parameter. +# If an explicit BSSID is specified, it must be chosen such that it: +# - results in a valid MASK that covers it and the dev_addr +# - is not the same as the MAC address of the radio +# - is not the same as any other explicitly specified BSSID +# +# Please note that hostapd uses some of the values configured for the first BSS +# as the defaults for the following BSSes. However, it is recommended that all +# BSSes include explicit configuration of all relevant configuration items. +# +#bss=wlan0_0 +#ssid=test2 +# most of the above items can be used here (apart from radio interface specific +# items, like channel) + +#bss=wlan0_1 +#bssid=00:13:10:95:fe:0b +# ... diff --git a/mini-ap-wifi/launch-wifi-ap-udhcpd.conf b/mini-ap-wifi/launch-wifi-ap-udhcpd.conf new file mode 100644 index 0000000..61be481 --- /dev/null +++ b/mini-ap-wifi/launch-wifi-ap-udhcpd.conf @@ -0,0 +1,122 @@ +# Sample udhcpd configuration file (/etc/udhcpd.conf) + +# The start and end of the IP lease block + +start 192.168.10.20 #default: 192.168.0.20 +end 192.168.10.254 #default: 192.168.0.254 + + +# The interface that udhcpd will use + +interface wlan0 #default: eth0 + + +# The maximim number of leases (includes addressesd reserved +# by OFFER's, DECLINE's, and ARP conficts + +#max_leases 254 #default: 254 + + +# If remaining is true (default), udhcpd will store the time +# remaining for each lease in the udhcpd leases file. This is +# for embedded systems that cannot keep time between reboots. +# If you set remaining to no, the absolute time that the lease +# expires at will be stored in the dhcpd.leases file. + +#remaining yes #default: yes + + +# The time period at which udhcpd will write out a dhcpd.leases +# file. If this is 0, udhcpd will never automatically write a +# lease file. (specified in seconds) + +#auto_time 7200 #default: 7200 (2 hours) + + +# The amount of time that an IP will be reserved (leased) for if a +# DHCP decline message is received (seconds). + +#decline_time 3600 #default: 3600 (1 hour) + + +# The amount of time that an IP will be reserved (leased) for if an +# ARP conflct occurs. (seconds + +#conflict_time 3600 #default: 3600 (1 hour) + + +# How long an offered address is reserved (leased) in seconds + +#offer_time 60 #default: 60 (1 minute) + +# If a lease to be given is below this value, the full lease time is +# instead used (seconds). + +#min_lease 60 #defult: 60 + + +# The location of the leases file + +#lease_file /var/lib/misc/udhcpd.leases #defualt: /var/lib/misc/udhcpd.leases + +# The location of the pid file +#pidfile /var/run/udhcpd.pid #default: /var/run/udhcpd.pid + +# Everytime udhcpd writes a leases file, the below script will be called. +# Useful for writing the lease file to flash every few hours. + +#notify_file #default: (no script) + +#notify_file dumpleases # <--- useful for debugging + +# The following are bootp specific options, setable by udhcpd. + +#siaddr 192.168.0.22 #default: 0.0.0.0 + +#sname zorak #default: (none) + +#boot_file /var/nfs_root #default: (none) + +# The remainer of options are DHCP options and can be specifed with the +# keyword 'opt' or 'option'. If an option can take multiple items, such +# as the dns option, they can be listed on the same line, or multiple +# lines. The only option with a default is 'lease'. + +#Examles +#opt dns 8.8.8.8 4.4.4.4 +# FDN open DNS resolvers +opt dns 80.67.169.12 80.67.169.40 +option subnet 255.255.255.0 +opt router 192.168.10.2 +option lease 864000 # 10 days of seconds + + +# Currently supported options, for more info, see options.c +#opt subnet +#opt timezone +#opt router +#opt timesrv +#opt namesrv +#opt dns +#opt logsrv +#opt cookiesrv +#opt lprsrv +#opt bootsize +#opt domain +#opt swapsrv +#opt rootpath +#opt ipttl +#opt mtu +#opt broadcast +#opt wins +#opt lease +#opt ntpsrv +#opt tftp +#opt bootfile +#opt wpad + +# Static leases map +#static_lease 00:60:08:11:CE:4E 192.168.0.54 +#static_lease 00:60:08:11:CE:3E 192.168.0.44 + + diff --git a/mini-ap-wifi/launch-wifi-ap.sh b/mini-ap-wifi/launch-wifi-ap.sh new file mode 100755 index 0000000..bb8bb9a --- /dev/null +++ b/mini-ap-wifi/launch-wifi-ap.sh @@ -0,0 +1,28 @@ +#!/bin/sh + + +ifconfig wlan0 192.168.10.2 netmask 255.255.255.0 + +echo 1 >/proc/sys/net/ipv4/ip_forward +iptables -t nat -A POSTROUTING -s 192.168.10.0/24 -j MASQUERADE + +udhcpd -f -S launch-wifi-ap-udhcpd.conf & +DHCPD_PID="$!" +hostapd ~/launch-wifi-ap-hostapd.conf & +HOSTAPD_PID="$!" + +sleep 5 +echo +echo +echo "Appuyer sur Entree pour quitter..." +read LINE + +kill -2 "$DHCPD_PID" +kill -2 "$HOSTAPD_PID" + +# Nettoyage +iptables -t nat -D POSTROUTING -s 192.168.10.0/24 -j MASQUERADE +echo 0 >/proc/sys/net/ipv4/ip_forward +ifconfig wlan0 down + + diff --git a/nagios/check_apache_access_log.pl b/nagios/check_apache_access_log.pl new file mode 100755 index 0000000..8dbf74f --- /dev/null +++ b/nagios/check_apache_access_log.pl @@ -0,0 +1,263 @@ +#!/usr/bin/perl + +# This perl script is an adaptation of logtail2 to parse +# Apache access logs. +# I know it's generally preferrable to require and call +# the original instead of forking and risking of not maintaining +# it but logtail is fairly simple and, since logtail2 is not always +# installed and somtimes not even packaged in distributions, +# it simplify deployment. +# TODO: call logtail2 if available ? + +# Copyright (C) 2003 Jonathan Middleton + +# This file is part of Logcheck. + +# Logcheck is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. + +# Logcheck is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with Logcheck; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +use strict; +use warnings; +use Getopt::Long; +use File::Basename; +use Digest::MD5 qw(md5_hex); +my ($size, $logfile, $offsetfile, @listingLogfiles, @listingOffsetfiles, $key, $firstTimeReading); +# (problems with including utils.pm) +my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4); +my $TMP_DIR = '/tmp'; +my %opts = (); +my %outputCpt = ( + '2XX' => 0, + '3XX' => 0, + '403' => 0, + '404' => 0, + '4XX' => 0, + '500' => 0, + '5XX' => 0, + 'others' => 0, # other (1XX) and strange things + ); +my ($outputTotalCpt) = 0; +my ($outputTotalBandwith) = 0; + +# process args and switches +my ($TEST_MODE) = 0; +# When we discover a file for the first time, +# we don't do the count and just mark the position +# for the next time +my ($COUNT_FIRST_READ_CATCHING_UP) = 0; +GetOptions( + 'file=s' => \@listingLogfiles, + 'even-catch-up' => \$COUNT_FIRST_READ_CATCHING_UP, + 'test-mode' => \$TEST_MODE, + ); + + +sub print_from_offset { + my ($filename, $offset) = @_; + # this subroutine prints the contents of the file named $filename, + # starting offset $offset. + #print "print_from_offset $filename, $offset\n"; + unless (open(LOGFILE, $filename)) { + print "File $logfile cannot be read: $!\n"; + exit $ERRORS{UNKNOWN}; + } + + seek(LOGFILE, $offset, 0); + + while () { + if ($_ =~ /^([[:xdigit:].:]+) (.+) (.+) (\[[[:alnum:]\/:]+ \+[[:digit:]]{4}\]) (".*") ([[:digit:]]{3}) ([[:digit:]]+) "(.*)" "(.*)"$/) { + #We ignore some IP address + next if ($1 eq '::1' or $1 eq '127.0.0.1' or $1 eq '2a01:e35:2ef3:b360::abac:22' or $1 eq '192.168.0.34'); + + if ($6 >= 200 && $6 < 300) { + ++$outputCpt{'2XX'}; + } elsif ($6 >= 300 && $6 < 400) { + ++$outputCpt{'3XX'}; + } elsif ($6 == 403) { + ++$outputCpt{'403'}; + } elsif ($6 == 404) { + ++$outputCpt{'404'}; + } elsif ($6 >= 400 && $6 < 500) { + ++$outputCpt{'4XX'}; + } elsif ($6 == 500) { + ++$outputCpt{'500'}; + } elsif ($6 >= 500 && $6 < 600) { + ++$outputCpt{'5XX'}; + } else { + ++$outputCpt{'others'}; + } + $outputTotalBandwith += $7; + } else { + ++$outputCpt{'others'}; + } + } + + $size = tell LOGFILE; + close LOGFILE; + return $size; +} + +sub mtime { + my ($filename) = @_; + my $mtime = 0; + unless (-e $filename && ($mtime = ((stat($filename))[8])) ) { + print STDERR "Cannot get $filename mtime: $!\n"; + exit 65; + } + return $mtime; +} + +sub inode { + my ($filename) = @_; + my $inode = 0; + unless (-e $filename && ($inode = ((stat($filename))[1])) ) { + print STDERR "Cannot get $filename inode: $!\n"; + exit 65; + } + return $inode; +} + +sub get_directory_contents { + my ($filename) = @_; + my $dirname = dirname($filename); + unless (opendir(DIR, $dirname)) { + print STDERR "Cannot open directory $dirname: $!\n"; + exit 65; + } + my @direntries = readdir(DIR); + closedir DIR; + return @direntries; +} + +sub determine_rotated_logfile { + my ($filename,$inode) = @_; + my $rotated_filename; + # this subroutine tries to guess to where a given log file was + # rotated. Its magic is mainly taken from logcheck's logoutput() + # function with dateext magic added. + + #print "determine_rotated_logfile $filename $inode\n"; + for my $codefile (glob("/usr/share/logtail/detectrotate/*.dtr")) { + my $func = do $codefile; + if (!$func) { + print STDERR "cannot compile $codefile: $!"; + exit 68; + } + $rotated_filename = $func->($filename); + last if $rotated_filename; + } + #if ($rotated_filename) { + # print "rotated_filename $rotated_filename (". inode($rotated_filename). ")\n"; + #} else { + # print "no rotated file found\n"; + #} + if ($rotated_filename && -e "$rotated_filename" && inode($rotated_filename) == $inode) { + return $rotated_filename; + } else { + return ""; + } +} +foreach $logfile (@listingLogfiles) { + my ($inode, $ino, $offset) = (0, 0, 0); + + if (! -f $logfile) { + print "File $logfile cannot be read: $!\n"; + exit $ERRORS{UNKNOWN}; + } + + # We generate a unique offset filename + $offsetfile = $TMP_DIR . '/nagios-logtail.' . md5_hex($logfile) . '.offset'; + $firstTimeReading = 0; + if (! -f $offsetfile) { + open(OFFSET, ">", $offsetfile); + chmod 0600, $offsetfile; + if (($ino,$size) = (stat($logfile))[1,7]) { + # Unless we care about the historic before the + # first call of this script, we just skip it. + if ($COUNT_FIRST_READ_CATCHING_UP) { + $size = 0; + } + print OFFSET "$ino\n$size\n"; + } + close OFFSET; + } + + + if ($offsetfile) { + # If offset file exists, open and parse it. + if (open(OFFSET, $offsetfile)) { + $_ = ; + if (defined $_) { + chomp $_; + $inode = $_; + $_ = ; + if (defined $_) { + chomp $_; + $offset = $_; + } + } + } + + # determine log file inode and size + unless (($ino,$size) = (stat($logfile))[1,7]) { + print "Cannot get $logfile file size: $!\n"; + exit $ERRORS{UNKNOWN}; + } + + if ($inode == $ino) { + # inode is still the same + next if $offset == $size; # short cut + if ($offset > $size) { + $offset = 0; + print "(warning: possible tampering on $logfile) " + } + } + + if ($inode != $ino) { + # this is the interesting case: inode has changed. + # So the file might have been rotated. We need to print the + # entire file. + # Additionally, we might want to see whether we can find the + # previous instance of the file and to process it from here. + #print "inode $inode, ino $ino\n"; + my $rotatedfile = determine_rotated_logfile($logfile,$inode); + if ( $rotatedfile && ! $firstTimeReading) { + print_from_offset($rotatedfile,$offset); + } + # print the actual file from beginning + $offset = 0; + } + } + + $size = print_from_offset($logfile,$offset); + + # update offset, unless test mode + unless ($TEST_MODE) { + unless (open(OFFSET, ">", $offsetfile)) { + print STDERR "File $offsetfile cannot be created. Check your permissions: $!\n"; + exit 73; + } + print OFFSET "$ino\n$size\n"; + close OFFSET; + } +} + +# printing results +print "OK|"; +foreach $key (sort keys %outputCpt) { + print "'" . $key . "'=" . $outputCpt{$key} . ";;;; " +} +print "'total bandwidth'=" . $outputTotalBandwith . "B;;;;\n"; +exit $ERRORS{'OK'}; diff --git a/nagios/check_apache_serverstatus.check_commands b/nagios/check_apache_serverstatus.check_commands new file mode 100644 index 0000000..5ad331e --- /dev/null +++ b/nagios/check_apache_serverstatus.check_commands @@ -0,0 +1 @@ +DATATYPE = GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,GAUGE,COUNTER,COUNTER,GAUGE diff --git a/nagios/check_apache_serverstatus.php b/nagios/check_apache_serverstatus.php new file mode 100644 index 0000000..1c5d2f1 --- /dev/null +++ b/nagios/check_apache_serverstatus.php @@ -0,0 +1,155 @@ +MACRO['TIMET'] != ""){ + $def[1] .= "VRULE:".$this->MACRO['TIMET']."#000000:\"Last Service Check \\n\" "; +} + + +// Request per Second +$opt[2] = " --vertical-label \"Anzahl\" --title \"Apache Requests per Second for $hostname\" --lower-limit 0 "; +$ds_name[2] = 'Server-Status'; +$def[2] = "DEF:var12=$RRDFILE[11]:$DS[11]:AVERAGE " ; +$def[2] .= "LINE1:var12#ffae2d:\"Requests per Second \" "; +$def[2] .= "GPRINT:var12:LAST:\"%4.0lf last\" " ; +$def[2] .= "GPRINT:var12:AVERAGE:\"%4.0lf avg\" " ; +$def[2] .= "GPRINT:var12:MAX:\"%4.0lf max\\n\" " ; + +// Bytes per Second and Bytes per Request +$opt[3] = " --vertical-label \"Anzahl\" --title \"Apache Bytes per ... for $hostname\" --lower-limit 0 "; +$ds_name[3] = 'Server-Status'; +$def[3] = "DEF:var13=$RRDFILE[2]:$DS[2]:AVERAGE " ; +$def[3] .= "DEF:var14=$RRDFILE[1]:$DS[1]:AVERAGE " ; +$def[3] .= "LINE1:var13#db60f7:\"Bytes per Second \" "; +$def[3] .= "GPRINT:var13:LAST:\"%4.0lf last\" " ; +$def[3] .= "GPRINT:var13:AVERAGE:\"%4.0lf avg\" " ; +$def[3] .= "GPRINT:var13:MAX:\"%4.0lf max\\n\" " ; +$def[3] .= "LINE1:var14#5fe27b:\"Bytes per Request \" "; +$def[3] .= "GPRINT:var14:LAST:\"%4.0lf last\" " ; +$def[3] .= "GPRINT:var14:AVERAGE:\"%4.0lf avg\" " ; +$def[3] .= "GPRINT:var14:MAX:\"%4.0lf max\\n\" " ; + +$opt[4] = " --vertical-label \"Anzahl\" --title \"Apache Total access and kBytes for $hostname\" --lower-limit 0 "; +$ds_name[4] = 'Server-Status'; +$def[4] = "DEF:var15=$RRDFILE[14]:$DS[14]:AVERAGE " + . "DEF:var16=$RRDFILE[15]:$DS[15]:AVERAGE " + . rrd::area('var16', '#004400') + . rrd::line1('var16', '#003300', 'Total_kBytes') + . rrd::gprint('var16', array('LAST', 'AVERAGE', 'MAX'), "%7.2lf %SkB/s") + . rrd::line1('var15', '#999999', 'Total_Accesses') + . rrd::gprint('var15', array('LAST', 'AVERAGE', 'MAX'), "%7.2lf %SHits/s"); diff --git a/nagios/check_apache_serverstatus.pl b/nagios/check_apache_serverstatus.pl new file mode 100755 index 0000000..c68e895 --- /dev/null +++ b/nagios/check_apache_serverstatus.pl @@ -0,0 +1,328 @@ +#!/usr/bin/perl -w + +# +# The MIT License (MIT) +# +# Copyright (c) 2016 Steffen Schoch - dsb it services GmbH & Co. KG +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +# +# Feel free to contact me via email: schoch@dsb-its.net +# + +# 2018-02-06, sni: 1.2 - fixed some bugs and typos, add some output - Thank you! +# 2016-08-03, schoch: 1.1 - changes for new apache version 2.4.x +# 2016-01-##, schoch: 1.0 - Init... + + +use strict; +use warnings; + +use Data::Dumper; +use Getopt::Long qw(:config bundling); # insert debug for much more infos ;) + + +# define constants +use constant { + VERSION => '1.0', + + # a simple inf variant - works for me ;-) + MAXINT => ~0, + NEGMAXINT => -1 * ~0, + + STAT_OK => 0, + STAT_WARNING => 1, + STAT_CRITICAL => 2, + STAT_UNKNOWN => 3 +}; + + +# check arguments +my $options = { # define defaults here + 'hostname' => 'localhost', + 'verbose' => 0, + 'wget' => '/usr/bin/wget', + 'wget-options' => '-q --no-check-certificate -O-', +}; +my $goodOpt = GetOptions( + 'v+' => \$options->{'verbose'}, + 'verbose+' => \$options->{'verbose'}, + 'V' => \$options->{'version'}, + 'h' => \$options->{'help'}, + 'version' => \$options->{'version'}, + 'help' => \$options->{'help'}, + + 'H=s' => \$options->{'hostname'}, + 'hostname=s' => \$options->{'hostname'}, + + 'wc=s' => \@{$options->{'warncrit'}}, + 'warncrit=s' => \@{$options->{'warncrit'}}, + + 'wget' => \$options->{'wget'}, + 'woptions=s' => \$options->{'wget-options'}, + + 'u=s' => \$options->{'url'}, + 'url=s' => \$options->{'url'}, +); +helpShort() unless $goodOpt; +helpLong() if $options->{'help'}; +if($options->{'version'}) { + print 'Version: ', VERSION, "\n"; + exit STAT_UNKNOWN; +} +print Data::Dumper->Dump([$options], ['options']) + if $options->{'verbose'}; + +# warncrit - get start and end for each pair +my $warncrit = {}; +foreach my $item (@{$options->{'warncrit'}}) { + if($item =~ m/^([^,]+),([^,]+),([^,]+)$/o) { + $warncrit->{$1} = {'w' => $2, 'c' => $3}; + } else { + mydie('Don\'t understand ' . $item); + } +} +print Data::Dumper->Dump([$warncrit], ['warncrit']) + if $options->{'verbose'}; + +# read stdin complete +local $/; + +# which url to use? --url can overwrite the auto-creation +my $url = $options->{'url'} + ? $options->{'url'} + : 'http://' . $options->{'hostname'} . '/server-status?auto'; +printf "Url: %s\n", $url + if $options->{'verbose'}; + +# open server info +open PH, sprintf('%s %s %s |', + $options->{'wget'}, + $options->{'wget-options'}, + $url +) or mydie('Can not open server-status: ' . $!); + +# read and cut data +my %lineData = map { (split /:\s*/)[0..1] } split /\n/, ; +close PH; +print Data::Dumper->Dump([\%lineData], ['server-status']) + if $options->{'verbose'}; + +# Search for "Scoreboard" and analyze... +my $data = {}; +if(exists $lineData{'Scoreboard'}) { + $data->{$1}++ while $lineData{'Scoreboard'} =~ m/(.)/og; +} else { + # Not found... + print 'No useful data found'; + exit STAT_UNKNOWN; +} +print Data::Dumper->Dump([$data], ['scoreboard']) + if $options->{'verbose'}; + +# Sum up Scoreboard entries +my $sum = 0; +foreach(keys %$data) { + $sum += $data->{$_}; +} + +# print result +my $result = $lineData{'ServerMPM'} ? sprintf('MPM=%s', $lineData{'ServerMPM'}) : ''; +my $perfData = ''; +my @statList = qw(_ S R W K D C L G I .); +my $stats = { + '_' => 'Wait', + 'S' => 'Start', + 'R' => 'Read', + 'W' => 'Send', + 'K' => 'Keepalive', + 'D' => 'DNS', + 'C' => 'Close', + 'L' => 'Logging', + 'G' => 'Graceful', + 'I' => 'Idle', + '.' => 'Free' +}; +foreach my $item (@statList) { + $result .= ', ' if $result; + $perfData .= ' ' if $perfData; + $result .= sprintf '%s=%d', $stats->{$item}, ($data->{$item} or 0); + $perfData .= sprintf '%s=%d', $stats->{$item}, ($data->{$item} or 0); +} +$result .= ' ===> Total=' . $sum; + +# add server rates - if exisiting (apache => 2.4) +if( + exists $lineData{'ReqPerSec'} + and exists $lineData{'BytesPerSec'} + and exists $lineData{'BytesPerReq'} +) { + $result .= sprintf ' RATES %s=%s, %s=%s, %s=%s', + (map { $_, $lineData{$_} } qw(ReqPerSec BytesPerSec BytesPerReq)); + $perfData .= sprintf ' %s=%s %s=%s %s=%s', + (map { $_, $lineData{$_} } qw(ReqPerSec BytesPerSec BytesPerReq)); + $perfData .= sprintf ' Total_Accesses=%sc', $lineData{"Total Accesses"}; + $perfData .= sprintf ' Total_kBytes=%s', $lineData{"Total kBytes"}; +} + +# check for warning and critical +my $status = STAT_OK; +foreach my $field (keys %$warncrit) { + printf "checking warn/crit for \"%s\"...\n", $field + if $options->{'verbose'}; + # value = if one letter scoreboard, else one of lineData (0 if not found) + my $fieldValue = + $field =~ m/^.$/o ? $data->{$field} || 0 : $lineData{$field} || 0; + printf " value: \"%s\"\n", $fieldValue + if $options->{'verbose'}; + my $fieldStatus = checkStatus($fieldValue, $warncrit->{$field}); + printf " result: %d\n", $fieldStatus + if $options->{'verbose'}; + # last if CRITICAL, save WARNING, ignore OK + if($fieldStatus == STAT_CRITICAL) { + $status = STAT_CRITICAL; + last; + } elsif($fieldStatus == STAT_WARNING) { + $status = STAT_WARNING; + } +} +printf "Check overall status: %d\n", $status + if $options->{'verbose'}; + + +# print result +printf "APACHE SERVER STATUS %s - %s|%s\n", + $status == 0 ? 'OK' : $status == 1 + ? 'WARNING' : $status == 2 + ? 'CRITICAL' : 'UNKNOWN', + $result, $perfData; +exit $status; + + +########### Functions ######################################################### + +# short help +sub helpShort { + print 'check_apache_serverstatus.pl -H [-h] [-v]', "\n", + '[--wc=] [--wget=] ', "\n", + '[--woption=] [-u ]', "\n"; + exit STAT_UNKNOWN; +} + + +# long help +sub helpLong { + print 'check_apache_serverstatus.pl (', VERSION, ")\n", + 'Steffen Schoch ', "\n", "\n", + < [-h] [-v] +[--wc=] [--wget=] +[--woption=] [-u ] + +Check apache server-status and builds performance data. Uses +wget to connect to the apache webserver. + +Options: + -h, --help + Print help + -V, --version + Print version + -H, --hostname + Host name or IP address - will be used as + http:///server-status. You can overwrite this + url by using -u/--url. + -v, --verbose + Be much more verbose. + --wget + Path to wget. Could also be used to use lynx or something + else instead of wget. Output must be send to stdout. + --woptions + Arguments passed to wget. + -u, --url + Use this url to connect to the apache server-status. Usefull + if the auto generated url out of the hostname is not correct. + --wc=, --warncrit= + Field could be any of the letters of the apache scoreboard or + of the other keys returned by server-status. Can be set multiple + times if you want to check more than one field. + +END + exit STAT_UNKNOWN; +} + + +# die with STAT_UNKNOWN +sub mydie { + print @_, "\n"; + exit STAT_UNKNOWN; +} + + +# checks if value is in defined limits for warning and critical +# see https://nagios-plugins.org/doc/guidelines.html for more details +# ARG1: value +# ARG2: hash with c and w limit +# RET: Nagios-State for this value +sub checkStatus { + my $value = shift; + my $limits = shift; + + # first check critical - if not crit, then check warning. If not must be ok + for my $type (qw(c w)) { + printf " checking type %s = %s\n", + $type eq 'c' ? 'critcal' : 'warning', + $limits->{$type} + if $options->{'verbose'}; + + # Get min/max values, range is inside or outside? + my $inOrOut = 'out'; + my $min; + my $max; + if($limits->{$type} =~ m/^(\@?)((~|\d*(\.\d+)?)?:)?(~|\d*(\.\d+)?)?$/o) { + # save min, max and inOrOut + $inOrOut = 'in' if $1; + $min = $3 || 0; + $max = $5 =~ m/^(.+)$/o ? $1 : MAXINT; # $max could be 0... + # neg infinity if ~ + ($min, $max) = map { $_ eq '~' ? NEGMAXINT : $_ } ($min, $max); + } else { + # Don't understand... + myexit('--> Strange range found: ', $limits->{$type}); + } + printf " inside or outside: %s min: %s max: %s\n", + $inOrOut, $min, $max + if $options->{'verbose'}; + + # check for value outside range. Break if match, else check for inside. + if($inOrOut eq 'out') { + if(!($min < $value && $value < $max)) { + return $type eq 'c' ? STAT_CRITICAL : STAT_WARNING; + } + } elsif($inOrOut eq 'in') { + if($min <= $value && $value <= $max) { + return $type eq 'c' ? STAT_CRITICAL : STAT_WARNING; + } + } + } + + # must be OK... + return STAT_OK; +} diff --git a/nagios/check_asterisk_dahdi_channels1.sh b/nagios/check_asterisk_dahdi_channels1.sh new file mode 100755 index 0000000..8eb2c19 --- /dev/null +++ b/nagios/check_asterisk_dahdi_channels1.sh @@ -0,0 +1,89 @@ +#!/bin/sh + +WARNING_RANGE="9:9" +CRITICAL_RANGE="8:10" + + +# Note needed in this version of the script +#set -e + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +. $PROGPATH/utils.sh + +# +# Fonction d'aide +# +usage() { + cat <&1 )" + +# Si la commande ne s'est pas correctement executée, +# on renvoie unknown +if [ "$?" -ne 0 ]; then + echo "UNKNOWN : error at command launch : $RESULT" + exit $STATE_UNKNOWN +fi +# Décompte +RESULT="$( printf "%s" "$RESULT" | tail -n +2 | sed 's/^.\{77\}[[:space:]]*//' | grep -c "In Service" )" + + +# Ventilation selon valeur +RETURN_STATUS=$STATE_OK +RETURN_OUTPUT="OK" +if check_range "$RESULT" "$CRITICAL_RANGE"; then + RETURN_STATUS=$STATE_CRITICAL + RETURN_OUTPUT="CRITICAL" +elif check_range "$RESULT" "$WARNING_RANGE"; then + RETURN_STATUS=$STATE_WARNING + RETURN_OUTPUT="WARNING" +fi + +# Affichage final +printf "%s | val=%d;%s;%s\n" "$RETURN_OUTPUT" "$RESULT" "$WARNING_RANGE" "$CRITICAL_RANGE" +exit $RETURN_STATUS diff --git a/nagios/check_asterisk_dahdi_status1.sh b/nagios/check_asterisk_dahdi_status1.sh new file mode 100644 index 0000000..f62fd22 --- /dev/null +++ b/nagios/check_asterisk_dahdi_status1.sh @@ -0,0 +1,89 @@ +#!/bin/sh + +WARNING_RANGE="4:4" +CRITICAL_RANGE="3:5" + + +# Note needed in this version of the script +#set -e + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +. $PROGPATH/utils.sh + +# +# Fonction d'aide +# +usage() { + cat <&1 )" + +# Si la commande ne s'est pas correctement executée, +# on renvoie unknown +if [ "$?" -ne 0 ]; then + echo "UNKNOWN : error at command launch : $RESULT" + exit $STATE_UNKNOWN +fi +# Décompte +RESULT="$( printf "%s" "$RESULT" | tail -n +2 | sed 's/^.\{41\}[[:space:]]*\([^[:space:]]\+\)[[:space:]]\+.*/\1/' | grep -c "OK" )" + + +# Ventilation selon valeur +RETURN_STATUS=$STATE_OK +RETURN_OUTPUT="OK" +if check_range "$RESULT" "$CRITICAL_RANGE"; then + RETURN_STATUS=$STATE_CRITICAL + RETURN_OUTPUT="CRITICAL" +elif check_range "$RESULT" "$WARNING_RANGE"; then + RETURN_STATUS=$STATE_WARNING + RETURN_OUTPUT="WARNING" +fi + +# Affichage final +printf "%s | val=%d;%s;%s\n" "$RETURN_OUTPUT" "$RESULT" "$WARNING_RANGE" "$CRITICAL_RANGE" +exit $RETURN_STATUS diff --git a/nagios/check_asterisk_sip_peers.sh b/nagios/check_asterisk_sip_peers.sh new file mode 100755 index 0000000..9dd58c1 --- /dev/null +++ b/nagios/check_asterisk_sip_peers.sh @@ -0,0 +1,184 @@ +#!/bin/sh + +# Note needed in this version of the script +#set -e + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +. $PROGPATH/utils.sh + +# +# Fonction d'aide +# +usage() { + cat <&1 )" + +# Si la commande ne s'est pas correctement executée, +# on renvoie unknown +if [ "$?" -ne 0 ]; then + echo "UNKNOWN : error at command launch : $RAW_OUTPUT" + exit $STATE_UNKNOWN +fi +# Décompte +RESULT="$( printf "%s" "$RAW_OUTPUT" | tail -n 1 | sed 's/^\([0-9]\+\) sip peers \[Monitored: \([0-9]\+\) online, \([0-9]\+\) offline Unmonitored: \([0-9]\+\) online, \([0-9]\+\) offline\]/\1\t\2\t\3\t\4\t\5/g' )" +VALUE_TOTAL_PEERS="$( printf "%s" "$RESULT" | cut -f 1 )" +VALUE_MONITORED_ONLINE_PEERS="$( printf "%s" "$RESULT" | cut -f 2 )" +VALUE_MONITORED_OFFLINE_PEERS="$( printf "%s" "$RESULT" | cut -f 3 )" +VALUE_UNMONITORED_ONLINE_PEERS="$( printf "%s" "$RESULT" | cut -f 4 )" +VALUE_UNMONITORED_OFFLINE_PEERS="$( printf "%s" "$RESULT" | cut -f 5 )" +# On extrait les lignes qui n'ont pas OK comme statut. Explication des sed : +# - on supprime la première et la dernière ligne +# - on supprime celles qui ont 'OK' en 95 position +# - on ne garde que le premier champ +# - on regroupe sur une ligne en séparant par des virgules +PROBLEMATIC_LINES="$( printf "%s" "$RAW_OUTPUT" | sed '1d;$d' | sed '/.\{94\}OK/d' | sed 's/[[:space:]].*//' | sed -e :a -e 'N; s/\n/, /; ta' )" + + +# Ventilation selon valeur +RETURN_STATUS=$STATE_OK +RETURN_OUTPUT="OK" + +# Warning checks +# - total +if [ -n "$WARNING_TOTAL_RANGE" ]; then + check_range "$VALUE_TOTAL_PEERS" "$WARNING_TOTAL_RANGE" + RET="$?" + if [ "$RET" -eq "2" ]; then + echo "ERROR with WARNING_TOTAL_RANGE" + exit $STATE_UNKNOWN + elif [ "$RET" -eq "0" ]; then + TMP="$VALUE_TOTAL_PEERS total peers" + if [ "$RETURN_STATUS" -ne "$STATE_WARNING" ]; then + RETURN_OUTPUT="$TMP" + else + RETURN_OUTPUT="$RETURN_OUTPUT, $TMP" + fi + RETURN_STATUS=$STATE_WARNING + fi +fi +# - monitored offline +if [ -n "$WARNING_MONITORED_OFFLINE_RANGE" ]; then + check_range "$VALUE_MONITORED_OFFLINE_PEERS" "$WARNING_MONITORED_OFFLINE_RANGE" + RET="$?" + if [ "$RET" -eq "2" ]; then + echo "ERROR with WARNING_MONITORED_OFFLINE_RANGE" + exit $STATE_UNKNOWN + elif [ "$RET" -eq "0" ]; then + TMP="$VALUE_MONITORED_OFFLINE_PEERS monitored offline peers" + if [ "$RETURN_STATUS" -ne "$STATE_WARNING" ]; then + RETURN_OUTPUT="$TMP" + else + RETURN_OUTPUT="$RETURN_OUTPUT, $TMP" + fi + RETURN_STATUS=$STATE_WARNING + fi +fi + +# Critical checks (copy-paste from warning + regexp s/CRITICAL/CRITICAL/g) +# - total +if [ -n "$CRITICAL_TOTAL_RANGE" ]; then + check_range "$VALUE_TOTAL_PEERS" "$CRITICAL_TOTAL_RANGE" + RET="$?" + if [ "$RET" -eq "2" ]; then + echo "ERROR with CRITICAL_TOTAL_RANGE" + exit $STATE_UNKNOWN + elif [ "$RET" -eq "0" ]; then + TMP="$VALUE_TOTAL_PEERS total peers" + if [ "$RETURN_STATUS" -ne "$STATE_CRITICAL" ]; then + RETURN_OUTPUT="$TMP" + else + RETURN_OUTPUT="$RETURN_OUTPUT, $TMP" + fi + RETURN_STATUS=$STATE_CRITICAL + fi +fi +# - monitored offline +if [ -n "$CRITICAL_MONITORED_OFFLINE_RANGE" ]; then + check_range "$VALUE_MONITORED_OFFLINE_PEERS" "$CRITICAL_MONITORED_OFFLINE_RANGE" + RET="$?" + if [ "$RET" -eq "2" ]; then + echo "ERROR with CRITICAL_MONITORED_OFFLINE_RANGE" + exit $STATE_UNKNOWN + elif [ "$RET" -eq "0" ]; then + TMP="$VALUE_MONITORED_OFFLINE_PEERS monitored offline peers" + if [ "$RETURN_STATUS" -ne "$STATE_CRITICAL" ]; then + RETURN_OUTPUT="$TMP" + else + RETURN_OUTPUT="$RETURN_OUTPUT, $TMP" + fi + RETURN_STATUS=$STATE_CRITICAL + fi +fi + + +# Affichage final +# Petit ajout dans l'indication +RETURN_OUTPUT_ADDENDUM="" +if [ -n "$PROBLEMATIC_LINES" ]; then + RETURN_OUTPUT_ADDENDUM="$( printf " (not ok peers : %s)" "$PROBLEMATIC_LINES" )" +fi +printf "%s%s | total=%d;%s;%s monitored_online=%d;%s;%s monitored_offline=%d;%s;%s unmonitored_online=%d;%s;%s unmonitored_offline=%d;%s;%s\n" "$RETURN_OUTPUT" "$RETURN_OUTPUT_ADDENDUM" \ + "$VALUE_TOTAL_PEERS" "$WARNING_TOTAL_RANGE" "$CRITICAL_TOTAL_RANGE" \ + "$VALUE_MONITORED_ONLINE_PEERS" "$WARNING_MONITORED_ONLINE_RANGE" "$CRITICAL_MONITORED_ONLINE_RANGE" \ + "$VALUE_MONITORED_OFFLINE_PEERS" "$WARNING_MONITORED_OFFLINE_RANGE" "$CRITICAL_MONITORED_OFFLINE_RANGE" \ + "$VALUE_UNMONITORED_ONLINE_PEERS" "$WARNING_UNMONITORED_ONLINE_RANGE" "$CRITICAL_UNMONITORED_ONLINE_RANGE" \ + "$VALUE_UNMONITORED_OFFLINE_PEERS" "$WARNING_UNMONITORED_OFFLINE_RANGE" "$CRITICAL_UNMONITORED_OFFLINE_RANGE" +exit $RETURN_STATUS diff --git a/nagios/check_bind9.pl b/nagios/check_bind9.pl new file mode 100755 index 0000000..c2ea5a9 --- /dev/null +++ b/nagios/check_bind9.pl @@ -0,0 +1,434 @@ +#!/usr/bin/perl +# +# host_check_bind.pl - Nagios BIND9 Monitoring Plugin - Host Check +# +# Indicate compatibility with the Nagios embedded perl interpreter +# nagios: +epn +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +my $COPYRIGHT = q{Copyright (C) 2010}; +my $VERSION = q{Version 1.0.0}; +my $AUTHOR = q{David Goh - http://goh.id.au/~david/}; +my $SOURCE = q{GIT: http://github.com/thorfi/nagios-bind9-plugin}; +my $LICENSE = + q{Licensed as GPLv3 or later - http://www.gnu.org/licenses/gpl.html}; + +# Force all stderr to stdout +*STDERR = *STDOUT; + +#use strict; +#use warnings; +use Carp (); +use English; +use Fcntl qw(:seek); +use Getopt::Long; +use IO::Handle; +use IO::File; + +# nagios exit codes +#0 OK UP +#1 WARNING UP or DOWN/UNREACHABLE* +#2 CRITICAL DOWN/UNREACHABLE +#3 UNKNOWN DOWN/UNREACHABLE +# Note: If the use_aggressive_host_checking option is enabled, return codes of +# 1 will result in a host state of DOWN or UNREACHABLE. Otherwise return codes +# of 1 will result in a host state of UP. +my $NAGIOS_EXIT_OK = 0; +my $NAGIOS_EXIT_WARNING = 1; +my $NAGIOS_EXIT_CRITICAL = 2; +my $NAGIOS_EXIT_UNKNOWN = 3; + +my %OPTIONS = ( + q{ps-path} => q{ps}, + q{pid-path} => q{/var/run/named.pid}, + q{rndc-path} => q{rndc}, + q{rndc-args} => q{}, + q{sudo-path} => q{}, + q{stats-path} => q{/var/run/named.stats}, + q{stats-seek} => 20480, + q{timeout} => 30, +); + +# Options to supply to ps command +# These commands are presumed to result in lines with the PID in +# column two (whitespace separated). +# Column two will be expected to match the whitespace trimmed contents +# of the --pid-path +my %PS_OPTS_FOR_OS = ( + q{darwin} => q{auxww}, + q{freebsd} => q{auxww}, + q{linux} => q{auxww}, + q{hpux} => q{-ef}, + q{irix} => q{-ef}, + q{openbsd} => q{auxww}, + q{solaris} => q{-ef}, + q{sunos} => q{auxww}, +); + +my $PS_OPTIONS = $PS_OPTS_FOR_OS{$OSNAME} || q{auxww}; + +my $print_help_sref = sub { + print qq{Usage: $PROGRAM_NAME + --pid-path: /path/to/named.pid (Default: $OPTIONS{'pid-path'}) +--stats-path: /path/to/named.stats (Default: $OPTIONS{'stats-path'}) + --ps-path: /path/to/bin/ps (Default: $OPTIONS{'ps-path'}) + --rndc-path: /path/to/sbin/rndc (Default: $OPTIONS{'rndc-path'}) + --sudo-path: /path/to/bin/sudo (Default: None) +--stats-seek: bytes to seek backwards to read last stats (Default: $OPTIONS{'stats-seek'}) + --rndc-args: additional args to rndc (Default: None) + --timeout: seconds to wait before dying (Default: $OPTIONS{'timeout'}) + --version: print version and exit + --help: print this help and exit + +$PROGRAM_NAME is a Nagios Plugin which checks that BIND9 is working +by checking the contents of --pid-path and checking that that process +is alive. + +If --rndc-args is set, the argument will have any semicolons, ampersands, +angle brackets and pipe characters removed, and then bit split on whitespace +and supplied as individual arguments in between 'rndc' and 'stats' + +If --pid-path is set to empty string or a non-existent file, no check +will be done. + +It also calls rndc status, rndc stats, and reports the latest statistics found +in --stats-path as well as gathered from rndc status + +If --sudo-path is specified then it will be used to call rndc +}; + + if ( not defined $PS_OPTS_FOR_OS{$OSNAME} ) { + print qq{ +Unknown \$OSNAME $OSNAME, please report to $AUTHOR with OSNAME and ps options +that will result in lines with the PID in column two (whitespace separated). +Column two of the output from ps will be expected to match the whitespace +trimmed contents of --pid-path +}; + } + + print qq{ +$COPYRIGHT +$VERSION +$AUTHOR +$SOURCE +$LICENSE +}; +}; + +my $print_version_sref = sub { + print qq{$VERSION - $COPYRIGHT - $AUTHOR}; +}; + +my $getopt_result = GetOptions( + "pid-path=s" => \$OPTIONS{'pid-path'}, + "rndc-path=s" => \$OPTIONS{'rndc-path'}, + "sudo-path=s" => \$OPTIONS{'sudo-path'}, + "stats-path=s" => \$OPTIONS{'stats-path'}, + "stats-seek=i" => \$OPTIONS{'stats-seek'}, + "rndc-args=s" => \$OPTIONS{'rndc-args'}, + "temp-path=s" => \$OPTIONS{'temp-path'}, + "timeout=i" => \$OPTIONS{'timeout'}, + "version" => sub { $print_version_sref->(); exit $NAGIOS_EXIT_UNKNOWN; }, + "help" => sub { $print_help_sref->(); exit $NAGIOS_EXIT_UNKNOWN; }, +); +if ( not $getopt_result ) { + print qq{Error: Options failure\n}; + $print_help_sref->(); + exit $NAGIOS_EXIT_UNKNOWN; +} + +$SIG{'ALRM'} = sub { + Carp::cluck(q{BIND9 plugin timed out}); + exit $NAGIOS_EXIT_WARNING; +}; +alarm $OPTIONS{'timeout'}; + +my @RNDC_ARGV = (); +if ( length $OPTIONS{'sudo-path'} ) { + push @RNDC_ARGV, $OPTIONS{'sudo-path'}; +} +push @RNDC_ARGV, $OPTIONS{'rndc-path'}; +if ( length $OPTIONS{'rndc-args'} ) { + my $args = $OPTIONS{'rndc-args'}; + $args =~ s/[;<>|&]//g; + push @RNDC_ARGV, split /\s+/, $args; +} + +my @RNDC_STATS = ( @RNDC_ARGV, q{stats}, ); +my @RNDC_STATUS = ( @RNDC_ARGV, q{status}, ); + +my @STATS_KEYS = qw( + success referral nxrrset nxdomain recursion failure duplicate dropped +); +my %STATS_ENDMAP = ( + 'queries resulted in successful answer' => 'success', + 'queries resulted in referral answer' => 'referral', + 'queries resulted in non authoritative answer' => 'referral', + 'queries resulted in nxrrset' => 'nxrrset', + 'queries resulted in NXDOMAIN' => 'nxdomain', + 'queries caused recursion' => 'recursion', + 'queries resulted in SERVFAIL' => 'failure', + 'duplicate queries received' => 'duplicate', + 'queries dropped' => 'dropped', +); + +# Regular expressions used to +# parse rndc stats data +my $STATS_RESET_RE = quotemeta q{+++ Statistics Dump +++}; + +my $STATS_STARTS_RE = + q{^(} . ( join q{|}, map { quotemeta $_ } @STATS_KEYS ) . q{)}; +my $STATS_ENDS_RE = + q{(} . ( join q{|}, map { quotemeta $_ } keys %STATS_ENDMAP ) . q{)$}; + +my @STATUS_KEYS = qw( + cpus + workers + zones + debug + xfers_running + xfers_deferred + soa_running + udp_running + udp_soft_limit + udp_hard_limit + tcp_running + tcp_hard_limit +); + +my @PERFKEYS = ( @STATS_KEYS, @STATUS_KEYS, ); +my %PERFDATA = map { ( $_ => 0, ) } @PERFKEYS; + +sub slurp_command { + my $fh = new IO::Handle; + open $fh, q{-|}, @_ or die qq{$!}; + return $fh->getlines(); +} + +my $BIND_PID; +if ( $OPTIONS{'pid-path'} ) { + my $path = $OPTIONS{'pid-path'}; + if ( -f $path ) { + my $fh = new IO::File $path, q{r}; + if ( not defined $fh ) { + print qq{BIND9 PID file at $path failed to open\n}; + exit $NAGIOS_EXIT_CRITICAL; + } + my $fh_line = $fh->getline(); + if ( not defined $fh_line ) { + print qq{BIND9 PID file $path is empty\n}; + exit $NAGIOS_EXIT_CRITICAL; + } + $BIND_PID = $fh_line; + $BIND_PID =~ s/^\s+//; + $BIND_PID =~ s/\s+$//; + if ( $BIND_PID !~ m/^\d+$/ ) { + print qq{BIND9 PID file $path did not contain a number\n}; + exit $NAGIOS_EXIT_CRITICAL; + } + my @ps_lines = slurp_command( $OPTIONS{'ps-path'}, $PS_OPTIONS ); + my $ps_found = 0; + for my $ps_line (@ps_lines) { + $ps_line =~ s/^\s+//; + my @bits = split /\s+/, $ps_line; + if ( ( int @bits ) < 2 ) { + next; + } + if ( $bits[1] eq $BIND_PID ) { + $ps_found = 1; + last; + } + } + if ( not $ps_found ) { + print + qq{BIND9 PID file $path contains not-running PID $BIND_PID\n}; + exit $NAGIOS_EXIT_CRITICAL; + } + } + else { + print qq{BIND9 PID file $path not found\n}; + exit $NAGIOS_EXIT_CRITICAL; + } +} + +my $exit_message = q{}; + +# Run rndc stats to put latest data in the stats-path +system @RNDC_STATS; + +# and slurp the latest data from stats-path +my $stats_fh = new IO::File $OPTIONS{'stats-path'}, q{r}; +if ( not defined $stats_fh ) { + $exit_message .= qq{Failed to open --stats-path }; + $exit_message .= $OPTIONS{'stats-path'}; + $exit_message .= qq{: $!.}; +} +else { + + # We have a stats file, so seek backwards in it and read it out. + + $stats_fh->seek( -$OPTIONS{'stats-seek'}, SEEK_END ); + my $found_stats_start = 0; + + while ( my $stats_line = $stats_fh->getline() ) { + chomp $stats_line; + $stats_line =~ s/^\s+//; + $stats_line =~ s/\s+$//; + if ( $stats_line =~ m/$STATS_RESET_RE/i ) { + + # Reset the stats, we have a new block + + $found_stats_start = 1; + for my $k (@STATS_KEYS) { + $PERFDATA{$k} = 0; + } + next; + } + if ( $stats_line =~ m/$STATS_STARTS_RE/i ) { + my $k = $1; + my @bits = split /\s+/, $stats_line; + my $number = $bits[-1]; + if ( $number =~ m/^\d+$/ ) { + $PERFDATA{$k} += $number; + } + next; + } + if ( $stats_line =~ m/$STATS_ENDS_RE/i ) { + my $k = $STATS_ENDMAP{$1}; + if ( not defined $k ) { + next; + } + my @bits = split /\s+/, $stats_line; + my $number = $bits[0]; + if ( $number =~ m/^\d+$/ ) { + $PERFDATA{$k} += $number; + } + next; + } + } + if ( not $found_stats_start ) { + $exit_message .= q{Failed to find statistics block in --stats-path }; + $exit_message .= $OPTIONS{'stats-path'}; + $exit_message .= q{.}; + } +} + +my $found_status_data = 0; + +# Run rndc status to slurp the bind9 status info +for my $status_line ( slurp_command(@RNDC_STATUS) ) { + if ( $status_line =~ m/CPUs found: (\d+)/i ) { + $PERFDATA{'cpus'} = $1; + } + elsif ( $status_line =~ m/worker threads: (\d+)/i ) { + $PERFDATA{'workers'} = $1; + } + elsif ( $status_line =~ m/number of zones: (\d+)/i ) { + $PERFDATA{'zones'} = $1; + } + elsif ( $status_line =~ m/debug level: (\d+)/i ) { + $PERFDATA{'debug'} = $1; + } + elsif ( $status_line =~ m/xfers running: (\d+)/i ) { + $PERFDATA{'xfers_running'} = $1; + } + elsif ( $status_line =~ m/xfers deferred: (\d+)/i ) { + $PERFDATA{'xfers_deferred'} = $1; + } + elsif ( $status_line =~ m/soa queries in progress: (\d+)/i ) { + $PERFDATA{'soa_running'} = $1; + } + elsif ( $status_line =~ m/recursive clients: (\d+)\/(\d+)\/(\d+)/i ) { + $PERFDATA{'udp_running'} = $1; + $PERFDATA{'udp_soft_limit'} = $2; + $PERFDATA{'udp_hard_limit'} = $3; + } + elsif ( $status_line =~ m/tcp clients: (\d+)\/(\d+)/i ) { + $PERFDATA{'tcp_running'} = $1; + $PERFDATA{'tcp_hard_limit'} = $2; + } + else { + + # Skip if we didn't match anything + next; + } + + # If we did match something, say so + $found_status_data = 1; +} + +if ( not $found_status_data ) { + $exit_message .= q{Failed to find status data in: '}; + $exit_message .= $OPTIONS{'rndc-path'}; + if ( length $OPTIONS{'rndc-args'} ) { + $exit_message .= q{ }; + $exit_message .= $OPTIONS{'rndc-args'}; + } + $exit_message .= q{ status'.}; +} + +my $exit_code = $NAGIOS_EXIT_OK; +if ( length $exit_message > 0 ) { + $exit_code = $NAGIOS_EXIT_WARNING; + $exit_message =~ s/[\r\n]/ /g; +} +else { + $exit_message = 'OK'; +} + +print qq{BIND9 $exit_message ;}; +if ( defined $BIND_PID ) { + print qq{ PID $BIND_PID ;}; +} +print q{ Running:}; +print qq{ $PERFDATA{'udp_running'}/$PERFDATA{'udp_soft_limit'}}; +print qq{/$PERFDATA{'udp_hard_limit'} UDP,}; +print qq{ $PERFDATA{'tcp_running'}/$PERFDATA{'tcp_hard_limit'} TCP,}; +print qq{ $PERFDATA{'xfers_running'} xfers;}; +print qq{ $PERFDATA{'xfers_deferred'} deferred xfers;}; +print qq{ $PERFDATA{'zones'} zones ;}; +print qq{ |}; + +# Generate perfdata in PNP4Nagios format +# http://docs.pnp4nagios.org/pnp-0.6/perfdata_format + +# Stats keys are all 'Counter' data +for my $k (@STATS_KEYS) { + print q{ } , $k , q{=} , $PERFDATA{$k} , q{c}; +} +my %EXTRAS = ( + q{debug} => ';1', # Warning if in debug +); +if ( $PERFDATA{'udp_soft_limit'} + $PERFDATA{'udp_hard_limit'} > 0 ) { + + # Running at soft limit is warning, running at hard limit is critical + + $EXTRAS{'udp_running'} = q{;} + . ( $PERFDATA{'udp_soft_limit'} || q{} ) . q{;} + . ( $PERFDATA{'udp_hard_limit'} || q{} ); +} +if ( $PERFDATA{'tcp_hard_limit'} ) { + + # Running at hard limit is critical + $EXTRAS{'tcp_running'} = q{;;} . $PERFDATA{'tcp_hard_limit'}; +} + +for my $k (@STATUS_KEYS) { + print q{ } , $k , q{=} , $PERFDATA{$k}; + if ( defined $EXTRAS{$k} ) { + print $EXTRAS{$k}; + } +} +exit $exit_code; diff --git a/nagios/check_crl b/nagios/check_crl new file mode 100644 index 0000000..48e7148 --- /dev/null +++ b/nagios/check_crl @@ -0,0 +1,199 @@ +#!/usr/bin/perl -w +# +# +# check_crl -f -w -c +# +# Script to check the "Next Update" time of a revocation list within the apache +# webserver (users.crl). +# Warn and crit are the number of days left before the expiration date is reached. +# +# Changes and Modifications +# ========================= +# 23.05.2007 - 1.0.0 R. Kaiser autinform +# Created +# + +use Time::Local; +use POSIX; +use strict; +use Getopt::Long; +use vars qw($opt_c $opt_w $opt_f $opt_h $opt_V); +use vars qw($PROGNAME); +use vars qw($REVISION); +use lib "/usr/lib/nagios/plugins" ; +use utils qw($TIMEOUT %ERRORS &print_revision &support &usage); + +# Programname and version +$PROGNAME = "check_crl"; +$REVISION = "\$Revision: 1.0.0 \$"; + +# Definition of my defaults +my $def_warn=10; +my $def_crit=4; + +sub print_help (); +sub print_usage (); +sub zeit_wandeln_in_sek (); + +Getopt::Long::Configure('bundling'); +GetOptions + ("V" => \$opt_V, "version" => \$opt_V, + "h" => \$opt_h, "help" => \$opt_h, + "f=s" => \$opt_f, "file=s" => \$opt_f, + "w=i" => \$opt_w, "warning=i" => \$opt_w, + "c=i" => \$opt_c, "critical=i" => \$opt_c); + +if ($opt_V) { + print_revision($PROGNAME,$REVISION); + exit $ERRORS{'OK'}; +} + +if ($opt_h) {print_help(); exit 0;} + +($opt_f) || ($opt_f = shift) || usage("File not specified\n"); +my $datei = $1 if ($opt_f =~ /^([\/-_.A-Za-z0-9]+)$/); +($datei) || usage("Invalid filename: $opt_f\n"); + +($opt_w) || ($opt_w = shift) || ($opt_w = $def_warn); +my $warn = $1 if ($opt_w =~ /^([0-9]{1,4})$/); +($warn) || usage("Invalid warning threshold: $opt_w\n"); + +($opt_c) || ($opt_c = shift) || ($opt_c = $def_crit); +my $crit = $1 if ($opt_c =~ /^([0-9]{1,4})$/); +($crit) || usage("Invalid critical threshold: $opt_c\n"); + + +# verify warning is less than critical +unless ( $warn > $crit ) { + usage("days left: warning ($opt_w) should be greater than critical ($opt_c)\n"); +} + +# check file access +unless ( -r $datei ) { + usage("File ($datei) not found or not accessable.\n"); +} + +# end of params checking + + +my $state = "OK"; +my $answer = undef; +my $res = undef; +my @lines = undef; +my $datum = undef; +my $monat= undef; +my $timesec = undef; + +# Just in case of problems, let's not hang Nagios +$SIG{'ALRM'} = sub { + print "No Answer from Client\n"; + exit $ERRORS{"UNKNOWN"}; +}; +alarm($TIMEOUT); + +########## Action + +# Get the "Next Update" line of the crl. +my $crl_zeit = qx(/usr/bin/openssl crl -noout -text -in $datei | /bin/grep " Next Update:"); +$crl_zeit =~ s/^ +//g; # remove leading blanks +$crl_zeit =~ s/\n$//; # remove trailing linefeed +$crl_zeit =~ s/ / /g; # remove multiple blanks + +my ($nix1, $nix2, $mon, $tag, $zeit, $jahr, $dattyp) = split (/ /, $crl_zeit); + +# change month from string to number +my $mon_liste = "JanFebMarAprMayJunJulAugSepOctNovDec"; +$monat = (index($mon_liste, $mon) / 3) + 1; + +# change to seconds since 01.01.1970 +$timesec = zeit_wandeln_in_sek(); + +# get current time and check the difference +my $act_time = time(); +my $SekDiff = $timesec - $act_time; +my $SekRest = $SekDiff; + +# make the difference human readable +my $Tage = int($SekRest / (24 * 3600)); +$SekRest = $SekRest - ($Tage * 24 * 3600); + +my $Stunden = int($SekRest / 3600); +$SekRest = $SekRest - ($Stunden * 3600); + +my $Minuten = int($SekRest / 60); +$SekRest = $SekRest - ($Minuten * 60); + +#Turn off alarm +alarm(0); + +# and now build the answer + +my $txt_Tage = "Tage"; +my $txt_Stun = "Stunden"; +my $txt_Minu = "Minuten"; +my $txt_Seku = "Sekunden"; +$txt_Tage = "Tag" if ( $Tage == 1 ); +$txt_Stun = "Stunde" if ( $Stunden == 1 ); +$txt_Minu = "Minute" if ( $Minuten == 1 ); +$txt_Seku = "Sekunde" if ( $SekRest == 1 ); + +$answer = "CRL Restzeit: $Tage $txt_Tage, $Stunden $txt_Stun, $Minuten $txt_Minu und $SekRest $txt_Seku.\n"; + +# check the time left with warn and crit + +if ( $SekDiff <= ($warn * 24 * 3600) ) { + $state = "WARNING"; +} +if ( $SekDiff <= ($crit * 24 * 3600) ) { + $state = "CRITICAL"; +} + +print $state." ".$answer; +exit $ERRORS{$state}; + + +############################################################################ + +sub zeit_wandeln_in_sek () { + + # Den Monat fuer Perl anpassen. + $monat = $monat - 1; + + # Die Zeitangabe auseinander nehmen. + my ($stunde,$minute,$sekunde) = split /\:/, $zeit; + + if ( $dattyp eq "GMT" ) { + my $timesec=timegm($sekunde,$minute,$stunde,$tag,$monat,$jahr); + } + elsif ( $dattyp eq "LOC" ) { + my $timesec=timelocal($sekunde,$minute,$stunde,$tag,$monat,$jahr); + } + else { + $timesec=0; + } +} + +### + +sub print_usage () { + print_revision($PROGNAME,$REVISION); + print "Usage: $PROGNAME -f [-w -c ]\n"; +} + +### + +sub print_help () { + print "Checking the expiration date (Next Update) of a revocation list. + +"; + print_usage(); + print " +-f, --filename=STRING + name and location of the revocation list file +-w, --warning=INTEGER + Number of days left (Defaults: $def_warn) +-c, --critical=INTEGER + Number of days left (Defaults: $def_crit) + +"; +} diff --git a/nagios/check_crl.sh b/nagios/check_crl.sh new file mode 100644 index 0000000..0e8dcc5 --- /dev/null +++ b/nagios/check_crl.sh @@ -0,0 +1,204 @@ +#!/bin/sh + +# Small script to survey CRL +# GPL v3+ + +# Default values +# Warning : 10 days - 10 years +RANGE_WARNING="864000:315360000" +# Critical : 4 days +RANGE_CRITICAL="345600:" + +# Output +OUTPUT_EXIT_STATUS=0 +OUTPUT_DETAIL_WARNING="" +OUTPUT_DETAIL_CRITICAL="" + +# Stop at the first non-catched error +set -e + +# +# Help function +# +usage() { + cat </dev/null 2>&1 ; then + echo "UNKNOWN 'openssl' not found." + exit 1 +fi + +# +# Parameters management +# +while getopts hw:c:f: OPT; do + case "$OPT" in + 'h') + usage + exit + ;; + + 'w') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_WARNING="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 'c') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_CRITICAL="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 'f') + # I'm not very proud of this one : aesthetically speaking, treatments + # should not be done during params management :) + CRL_FILE="$OPTARG" + if [ ! -f "$CRL_FILE" ]; then + echo "UNKNOWN: inexistent file." + exit 3 + fi + + # Extract time left, in seconds + EXPIRATION_DATE="$( openssl crl -noout -text -in "$CRL_FILE" | sed -n "s/^[[:space:]]\+Next Update: \(.*\)$/\1/p" )" + if [ -z "$EXPIRATION_DATE" ]; then + echo "UNKNOWN: couldn't get expiration date." + exit 3 + fi + TIME_LEFT=$(( $( date +%s ) - $( date --date="$EXPIRATION_DATE" +%s ) )) + + # Check time left against range + if ! check_range "$TIME_LEFT" "$RANGE_CRITICAL"; then + OUTPUT_EXIT_STATUS=2 + OUTPUT_DETAIL_CRITICAL="$OUTPUT_DETAIL_CRITICAL crl:$CRL_FILE" + elif ! check_range "$CPT" "$RANGE_WARNING"; then + if [ "$OUTPUT_EXIT_STATUS" -eq 0 ]; then + OUTPUT_EXIT_STATUS=1 + fi + OUTPUT_DETAIL_WARNING="$OUTPUT_DETAIL_WARNING crl:$CRL_FILE" + fi + ;; + + \?) + usage + exit 1 + ;; + esac +done + +case "$OUTPUT_EXIT_STATUS" in + '0') + printf "OK" + ;; + '1') + printf "WARNING %s" "$OUTPUT_DETAIL_WARNING" + ;; + '2') + printf "CRITICAL %s" "$OUTPUT_DETAIL_CRITICAL" + ;; + *) + printf "UNKNOWN" + ;; +esac + +# on supprime les retours à la ligne +exit $RETURN_STATUS + diff --git a/nagios/check_dane_tlsa.sh b/nagios/check_dane_tlsa.sh new file mode 100755 index 0000000..076a71b --- /dev/null +++ b/nagios/check_dane_tlsa.sh @@ -0,0 +1,118 @@ +#!/bin/sh + +# Not needed in this version of the script +set -e + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +. $PROGPATH/utils.sh + +# +# Help function +# +usage() { + cat </dev/null 2>&1 + if [ "$?" -eq "2" ]; then + return 1 + fi + return 0 +} + +# Some early checks +if ! which find >/dev/null 2>&1 ; then + echo "UNKNOWN 'find' not found." + exit 1 +fi + +# +# Gestion des paramètres +# +while getopts hs:v f; do + case "$f" in + 'h') + usage + exit + ;; + + + 's') + # Yeah, I don't manage server name with space in it... Sorry... + # If you find a elegant way to do it, please mail ! + SERVERS_LIST="$SERVERS_LIST $OPTARG" + ;; + + 'v') + DEBUG_MODE="-v" + ;; + + \?) + usage + exit 1 + ;; + esac +done +shift $( expr $OPTIND - 1 ) +TARGETS_LIST="$@" + +if [ -z "$SERVERS_LIST" ]; then + OUTPUT_EXIT_STATUS=$STATE_UNKNOWN + OUTPUT_DETAIL_UNKNOWN="$OUTPUT_DETAIL_UNKNOWN (no server specified)" +else + for SERVER in $SERVERS_LIST; do + for TARGET in $TARGETS_LIST; do + if [ $( rsync $RSYNC_OPTIONS "$TARGET" "$SERVER:$TARGET" 2>&1 | wc -l ) -gt 0 ]; then + OUTPUT_EXIT_STATUS=$STATE_CRITICAL + OUTPUT_DETAIL_CRITICAL="$OUTPUT_DETAIL_CRITICAL $SERVER:$TARGET" + if [ -n "$DEBUG_MODE" ]; then + echo rsync $RSYNC_OPTIONS "$TARGET" "$SERVER:$TARGET" + rsync $RSYNC_OPTIONS "$TARGET" "$SERVER:$TARGET" + fi + fi + done + done +fi + +case "$OUTPUT_EXIT_STATUS" in + '0') + printf "OK" + ;; + '1') + printf "WARNING %s" "$OUTPUT_DETAIL_WARNING" + ;; + '2') + printf "CRITICAL %s" "$OUTPUT_DETAIL_CRITICAL" + ;; + *) + printf "UNKNOWN %s" "$OUTPUT_DETAIL_UNKNOWN" + ;; +esac + +# (pas de perfdata dans ce script) +#printf "|%s\n" "$OUTPUT_PERFDATA" +printf "\n" +# on supprime les retours à la ligne +exit $OUTPUT_EXIT_STATUS diff --git a/nagios/check_drupal_multi.sh b/nagios/check_drupal_multi.sh new file mode 100755 index 0000000..130d4ee --- /dev/null +++ b/nagios/check_drupal_multi.sh @@ -0,0 +1,111 @@ +#!/bin/sh + +# This script's purpose is to launch check_drupal with URL and +# password stored in a listing file. +# +# memento : +# drush en nagios +# drush vset nagios_page_path NAGIOS_PATH +# drush vset nagios_ua NAGIOS_PASSWORD + +# Default options +NAGIOS_PLUGIN="/usr/lib/nagios/plugins/check_drupal" +DATABASE="/etc/nagios-plugins/check_drupal_multi.lst" + +# Par défaut, on arrête le script à la première erreur non "catchée" +set -e + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +. $PROGPATH/utils.sh + +# Fonctions +# affiche le message d'aide +usage() { +cat <&2 + exit 1 + ;; + esac +done +#(code inutile, mais que je garde parce qu'on ne sait jamais) +#shift $( expr $OPTIND - 1 ) +#DATA="$1" + +# Petite vérif. +if [ ! -f "$DATABASE" ]; then + echo "UNKNOWN: no check_drupal_multi listing found." + exit $STATE_UNKNOWN +fi +if [ ! -f "$NAGIOS_PLUGIN" ]; then + echo "UNKNOWN: check_drupal could not be found." + exit $STATE_UNKNOWN +fi + +# Lookup for host in database +DATABASE_LINE="$( grep -w "^$NAGIOS_HOST" "$DATABASE" | head -n 1 )" +NAGIOS_DRUPAL_UID="$( printf "$DATABASE_LINE" | cut -f 2 )" +NAGIOS_DRUPALPATH="$( printf "$DATABASE_LINE" | cut -f 3 )" +NAGIOS_TIMEOUT="$( printf "$DATABASE_LINE" | cut -f 4 )" +if [ -z "$NAGIOS_TIMEOUT" ]; then + NAGIOS_TIMEOUT="$NAGIOS_DEFAULT_TIMEOUT" +fi + +# Check we actually got a host +if [ -z "$NAGIOS_DRUPAL_UID" ]; then + echo "UNKNOWN: Host not found in listing file." + exit $STATE_UNKNOWN +fi + +# Launch the actual plugin with config +$NAGIOS_PLUGIN -H "$NAGIOS_HOST" -U "$NAGIOS_DRUPAL_UID" \ + $( test -n "$NAGIOS_DRUPALPATH" && printf "%s %s" "-P" "$NAGIOS_DRUPALPATH" ) \ + $( test -n "$NAGIOS_TIMEOUT" && printf "%s %s" "-t" "$NAGIOS_TIMEOUT" ) diff --git a/nagios/check_file_age.sh b/nagios/check_file_age.sh new file mode 100755 index 0000000..b342996 --- /dev/null +++ b/nagios/check_file_age.sh @@ -0,0 +1,160 @@ +#!/bin/sh + +# Petit script custom pour vérifier l'âge de certains fichiers +# GPL v3+ + +# Default values +RANGE_WARNING_AGE="7" +RANGE_CRITICAL_AGE="30" +RANGE_WARNING_FILES_NUMBER="1:" +RANGE_CRITICAL_FILES_NUMBER="1:" +FIND_BASEDIR="/" + +# Output +OUTPUT_EXIT_STATUS=0 +OUTPUT_DETAIL_WARNING="" +OUTPUT_DETAIL_CRITICAL="" +OUTPUT_PERFDATA="" + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +# Stop at the first non-catched error +set -e + +# Include check_range() +. $PROGPATH/utils.sh + +# +# Fonction d'aide +# +usage() { + cat </dev/null 2>&1 + if [ "$?" -eq "2" ]; then + return 1 + fi + return 0 +} + +# Some early checks +if ! which find >/dev/null 2>&1 ; then + echo "UNKNOWN 'find' not found." + exit 1 +fi + +# +# Gestion des paramètres +# +while getopts hw:c:W:C:b:f: f; do + case "$f" in + 'h') + usage + exit + ;; + + 'w') + RANGE_WARNING_AGE="$( printf "%d" "$OPTARG" )" + ;; + + 'c') + RANGE_CRITICAL_AGE="$( printf "%d" "$OPTARG" )" + ;; + + 'W') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_WARNING_FILES_NUMBER="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 'C') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_CRITICAL_FILES_NUMBER="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 'b') + # TODO : vérifier que le répertoire existe ? + FIND_BASEDIR="$OPTARG" + ;; + + 'f') + # Ce n'est pas très propre, mais on gère tout ici plutôt que de remplir + # un buffer et de le traiter ensuite + FIND_NAME_REGEXP="$OPTARG" + + # mémo : 'label'=value[UOM];[warn];[crit];[min];[max] + #OUTPUT_PERFDATA=$( printf "%s'port%d'=%d;%s;%s;0;" \ + # "$( test -n "$OUTPUT_PERFDATA" && echo "$OUTPUT_PERFDATA " )" \ + # "$PORT_NUMBER" \ + # "$CPT" \ + # "$RANGE_WARNING" \ + # "$RANGE_CRITICAL" ) + + FILES_NUMBER_AT_WARN_AGE="$( find "$FIND_BASEDIR" -name "$FIND_NAME_REGEXP" -type f -mtime "-$RANGE_WARNING_AGE" -printf "a\n" | wc -l )" + FILES_NUMBER_AT_CRIT_AGE="$( find "$FIND_BASEDIR" -name "$FIND_NAME_REGEXP" -type f -mtime "-$RANGE_CRITICAL_AGE" -printf "a\n" | wc -l )" + + if check_range "$FILES_NUMBER_AT_CRIT_AGE" "$RANGE_CRITICAL_FILES_NUMBER" ; then + OUTPUT_EXIT_STATUS=2 + OUTPUT_DETAIL_CRITICAL="$OUTPUT_DETAIL_CRITICAL basedir:$FIND_BASEDIR($FILES_NUMBER_AT_CRIT_AGE files at less than $RANGE_CRITICAL_AGE days)" + elif check_range "$FILES_NUMBER_AT_WARN_AGE" "$RANGE_WARNING_FILES_NUMBER"; then + if [ "$OUTPUT_EXIT_STATUS" -eq 0 ]; then + OUTPUT_EXIT_STATUS=1 + fi + OUTPUT_DETAIL_WARNING="$OUTPUT_DETAIL_WARNING basedir:$FIND_BASEDIR($FILES_NUMBER_AT_WARN_AGE files at less than $RANGE_WARNING_AGE days)" + fi + ;; + + \?) + usage + exit 1 + ;; + esac +done + +case "$OUTPUT_EXIT_STATUS" in + '0') + printf "OK" + ;; + '1') + printf "WARNING %s" "$OUTPUT_DETAIL_WARNING" + ;; + '2') + printf "CRITICAL %s" "$OUTPUT_DETAIL_CRITICAL" + ;; + *) + printf "UNKNOWN" + ;; +esac + +# (pas de perfdata dans ce script) +#printf "|%s\n" "$OUTPUT_PERFDATA" +printf "\n" +# on supprime les retours à la ligne +exit $OUTPUT_EXIT_STATUS diff --git a/nagios/check_first_ip.sh b/nagios/check_first_ip.sh new file mode 100755 index 0000000..0c5de34 --- /dev/null +++ b/nagios/check_first_ip.sh @@ -0,0 +1,112 @@ +#!/bin/sh + +# Petit script pour vérifier qu'une IP souhaitée est en tête des IP configurées +# GPL v3+ (copyright chl-dev@bugness.org) + +# Initialisation +IGNORED_ADDRESS="127.0.0. ::1 fe80:" + +# Output +OUTPUT_EXIT_STATUS=0 +OUTPUT_DETAIL_WARNING="" +OUTPUT_DETAIL_CRITICAL="" +OUTPUT_PERFDATA="" + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +# Stop at the first non-catched error +set -e + +# Include check_range() +. $PROGPATH/utils.sh + +# +# Fonction d'aide +# +usage() { + cat </dev/null 2>&1 + if [ "$?" -eq "2" ]; then + return 1 + fi + return 0 +} + +# Some early checks +for i in netstat ss; do + if which "$i" >/dev/null 2>&1 ; then + COMMAND_SYS="$i" + if [ "$COMMAND_SYS" = "ss" ]; then + OUTPUT_COLUMN=5 + else + OUTPUT_COLUMN=4 + fi + break + fi +done +if [ -z "$COMMAND_SYS" ]; then + echo "UNKNOWN 'netstat' and 'ss' not found." + exit 1 +fi + +# +# Gestion des paramètres +# +while getopts hw:c:p: f; do + case "$f" in + 'h') + usage + exit + ;; + + 'w') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_WARNING="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 'c') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_CRITICAL="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 'p') + # Ce n'est pas très propre, mais on gère tout ici plutôt que de remplir + # un buffer et de le traiter ensuite + # Note : grep renvoie un code d'erreur 1 s'il n'y a pas de résultat, + # d'où l'ajout d'un || true sur lui uniquement. + LABEL="$OPTARG" + case "$OPTARG" in + 'all') + CPT="$( $COMMAND_SYS -taun | tail -n +2 | wc -l )" + PORT_NUMBER='all' + ;; + 'all-ipv4') + CPT="$( $COMMAND_SYS -taun4 | tail -n +2 | wc -l )" + PORT_NUMBER='all-ipv4' + ;; + 'all-ipv6') + CPT="$( $COMMAND_SYS -taun6 | tail -n +2 | wc -l )" + PORT_NUMBER='all-ipv6' + ;; + 'listen') + CPT="$( $COMMAND_SYS -tlun | tail -n +2 | wc -l )" + PORT_NUMBER='listen' + ;; + 'listen-ipv4') + CPT="$( $COMMAND_SYS -tlun4 | tail -n +2 | wc -l )" + PORT_NUMBER='listen-ipv4' + ;; + 'listen-ipv6') + CPT="$( $COMMAND_SYS -tlun6 | tail -n +2 | wc -l )" + PORT_NUMBER='listen-ipv6' + ;; + 'listen-unix') + CPT="$( $COMMAND_SYS -xl | tail -n +2 | wc -l )" + PORT_NUMBER='listen-unix' + ;; + 'listen-unix:'*) + CPT="$( $COMMAND_SYS -xl | tail -n +2 | grep "$( echo "$OPTARG" | sed 's/^listen-unix://' )" | wc -l )" + PORT_NUMBER=$OPTARG # risque de bug côté superviseur ? + ;; + *) + PORT_NUMBER=$( printf "%d" "$OPTARG" ) + LABEL="port$PORT_NUMBER" + CPT="$( $COMMAND_SYS -taun | sed 's/[[:space:]]\+/\t/g' | cut -f "$OUTPUT_COLUMN" | ( grep -c ":$PORT_NUMBER$" || true ) )" + ;; + esac + + # mémo : 'label'=value[UOM];[warn];[crit];[min];[max] + OUTPUT_PERFDATA=$( printf "%s'%s'=%d;%s;%s;0;" \ + "$( test -n "$OUTPUT_PERFDATA" && echo "$OUTPUT_PERFDATA " )" \ + "$LABEL" \ + "$CPT" \ + "$RANGE_WARNING" \ + "$RANGE_CRITICAL" ) + + if check_range "$CPT" "$RANGE_CRITICAL"; then + OUTPUT_EXIT_STATUS=2 + OUTPUT_DETAIL_CRITICAL="$OUTPUT_DETAIL_CRITICAL Port:$PORT_NUMBER($CPT conn.)" + elif check_range "$CPT" "$RANGE_WARNING"; then + if [ "$OUTPUT_EXIT_STATUS" -eq 0 ]; then + OUTPUT_EXIT_STATUS=1 + fi + OUTPUT_DETAIL_WARNING="$OUTPUT_DETAIL_WARNING Port:$PORT_NUMBER($CPT conn.)" + fi + ;; + + \?) + usage + exit 1 + ;; + esac +done + +case "$OUTPUT_EXIT_STATUS" in + '0') + printf "OK ($COMMAND_SYS)" + ;; + '1') + printf "WARNING ($COMMAND_SYS) %s" "$OUTPUT_DETAIL_WARNING" + ;; + '2') + printf "CRITICAL ($COMMAND_SYS) %s" "$OUTPUT_DETAIL_CRITICAL" + ;; + *) + printf "UNKNOWN" + ;; +esac + +printf "|%s\n" "$OUTPUT_PERFDATA" +# on supprime les retours à la ligne +exit $OUTPUT_EXIT_STATUS diff --git a/nagios/check_network-neighbour-table.sh b/nagios/check_network-neighbour-table.sh new file mode 100755 index 0000000..0157ef6 --- /dev/null +++ b/nagios/check_network-neighbour-table.sh @@ -0,0 +1,68 @@ +#!/bin/sh + +# Petit script custom pour relever les compteurs des tables +# de voisins (neighbour) ipv4 (ARP) et ipv6 (Neighbour discorvery) + +# +# Fonction d'aide +# +usage() { + cat </dev/null 2>&1 || [ "$( ip ntable show | wc -l )" -lt 2 ]; then + echo "UNKNOWN souci avec 'ip ntable show'." + exit 1 +fi + +# On lance la commande +printf "OK|" + +# Dans l'ordre : +# - la commande... +# - tout sur 1 ligne +# - 1 ligne = 1 couple interface - protocole +# - on picore les quelques éléments intéressants (uniquement refcnt pour le moment) +# - on remet tout sur une ligne +# - pas d'espace en fin de ligne +ip ntable show \ + | tr '\n' '@' \ + | sed 's/@@/\n/g' \ + | sed -n 's/^\(inet6\?\).*dev\s\+\(\S\+\).*\(refcnt\)\s\+\([0-9]\+\).*/\1_\2\3=\4/gp' \ + | tr '\n' ' ' \ + | sed 's/\s\+$/\n/' + +exit 0 diff --git a/nagios/check_network_volume.sh b/nagios/check_network_volume.sh new file mode 100755 index 0000000..776c2d0 --- /dev/null +++ b/nagios/check_network_volume.sh @@ -0,0 +1,17 @@ +#!/bin/sh + + +printf "OK |" + +for i in $( cat /proc/net/dev | sed -n 's/^[[:space:]]*\([a-z0-9\.]\+\):.*/\1/p' ); do + if [ $( echo "$i" | egrep -c '(lo|bond|vmbr)' ) -gt 0 ]; then + continue + fi + VOLUME_RECU="$( cat /proc/net/dev | sed -n "s/^[[:space:]]*$i:[[:space:]]*//p" | sed 's/[[:space:]]\+/ /g' | cut -d " " -f 1 )" + VOLUME_EMIS="$( cat /proc/net/dev | sed -n "s/^[[:space:]]*$i:[[:space:]]*//p" | sed 's/[[:space:]]\+/ /g' | cut -d " " -f 9 )" + PAQUETS_RECUS="$( cat /proc/net/dev | sed -n "s/^[[:space:]]*$i:[[:space:]]*//p" | sed 's/[[:space:]]\+/ /g' | cut -d " " -f 2 )" + PAQUETS_EMIS="$( cat /proc/net/dev | sed -n "s/^[[:space:]]*$i:[[:space:]]*//p" | sed 's/[[:space:]]\+/ /g' | cut -d " " -f 10 )" + printf " %s_packets_in=%d %s_packets_out=%d %s_volume_in=%d %s_volume_out=%d" "$i" "$PAQUETS_RECUS" "$i" "$PAQUETS_EMIS" "$i" "$VOLUME_RECU" "$i" "$VOLUME_EMIS" +done + +printf "\n" diff --git a/nagios/check_nrpe_stunnel.sh b/nagios/check_nrpe_stunnel.sh new file mode 100755 index 0000000..4d5f1f8 --- /dev/null +++ b/nagios/check_nrpe_stunnel.sh @@ -0,0 +1,127 @@ +#!/bin/sh + +# This script's purpose is to launch check_nrpe through stunnel +# in a transparent way +# - Nagios/Shinken launch "check_nrpe_stunnel -H host -c command" +# - this script looks up in a database (-d option) to redirect the +# call to the local port of the stunnel +# +# This script needs : +# - nrpe daemon on the remote host +# - stunnel in server mode on the remote host +# - stunnel in client mode on the local (nagios/shinken) host +# - a database (cf help message) + +# TODO : copy stunnel conf. + +# Default options +NAGIOS_CHECKNRPE="/usr/lib/nagios/plugins/check_nrpe" +DATABASE="/etc/nagios/check_nrpe_stunnel.lst" + +# Par défaut, on arrête le script à la première erreur non "catchée" +set -e + +PROGPATH=$( echo $0 | sed -e 's,[\\/][^\\/][^\\/]*$,,' ) +REVISION="0.1" + +. $PROGPATH/utils.sh + +# Fonctions +# affiche le message d'aide +usage() { +cat < -C -H -c ... (cf. check_nrpe_options) + $0 -h + + -h : ce message d'aide + +Database is a text file with two fields, separated by tabulation. The first +is the local port for stunnel to join the host in the second field. +Example : +5678 bdd.localdomain +5679 proxmox.localdomain +5680 backup.localdomain + +(for examples of how to setup stunnel, cf. comments in this script) + +Default options : + Database : $DATABASE + check_nrpe path : $NAGIOS_CHECKNRPE +EOF +} + + +# Début du code +# gestion des options de lancement +while getopts d:H:c:C:nut:a: f; do + case $f in + 'a') + NAGIOS_ARGLIST="$OPTARG" + ;; + + 'c') + NAGIOS_COMMAND="$OPTARG" + ;; + + 'C') + NAGIOS_CHECKNRPE="$OPTARG" + ;; + + 'd') + DATABASE="$OPTARG" + ;; + + 'H') + NAGIOS_HOST="$OPTARG" + ;; + + 'n') + NAGIOS_NOSSL="1" + ;; + + 't') + NAGIOS_TIMEOUT="$OPTARG" + ;; + 'u') + NAGIOS_SOCKET_NONCRITICALTIMEOUT="1" + ;; + + 'h') + usage + exit 0 + ;; + + \?) + usage >&2 + exit 1 + ;; + esac +done +#(code inutile, mais que je garde parce qu'on ne sait jamais) +#shift $( expr $OPTIND - 1 ) +#DATA="$1" + +# Petite vérif. +if [ ! -f "$DATABASE" ]; then + echo "UNKNOWN: no check_nrpe_stunnel database found." + exit $STATE_UNKNOWN +fi +if [ ! -f "$NAGIOS_CHECKNRPE" ]; then + echo "UNKNOWN: check_nrpe_stunnel could not find check_nrpe (-C flag)." + exit $STATE_UNKNOWN +fi + +# Lookup for host in database +STUNNEL_PORT="$( grep -w "^$NAGIOS_HOST" "$DATABASE" | head -n 1 | cut -f 2 )" + +if [ -z "$STUNNEL_PORT" ]; then + echo "UNKNOWN: Host not found in check_nrpe_stunnel database." + exit $STATE_UNKNOWN +fi + +$NAGIOS_CHECKNRPE -H localhost -p $STUNNEL_PORT \ + $( test -n "$NAGIOS_SOCKET_NONCRITICALTIMEOUT" && printf "%s" "-u" ) \ + $( test -n "$NAGIOS_NOSSL" && printf "%s" "-n" ) \ + $( test -n "$NAGIOS_TIMEOUT" && printf "%s %d" "-t" "$NAGIOS_TIMEOUT" ) \ + $( test -n "$NAGIOS_COMMAND" && printf "%s %s" "-c" "$NAGIOS_COMMAND" ) \ + $( test -n "$NAGIOS_ARGLIST" && printf "%s %s" "-a" "$NAGIOS_ARGLIST" ) diff --git a/nagios/check_postfix_log.sh b/nagios/check_postfix_log.sh new file mode 100755 index 0000000..22e9caf --- /dev/null +++ b/nagios/check_postfix_log.sh @@ -0,0 +1,49 @@ +#!/bin/sh + +TMPFILE=$( mktemp ) +LOG=/var/log/mail.log +LOGTAIL_OFFSET=/tmp/logtail-maillog.offset +EXIT_STATUS=0 + +# Alors, petite explication +# Dans l'ordre : +# - logtail sur le log de Postfix +# - pflogsumm pour avoir les stats +# - head : on ne prend que les premières stats +# - sed (.*) : on dégage tout ce qui est entre parenthèse (les labels +# doivent être identiques d'un appel à l'autre, les valeurs contenues +# dans les parenthèses ne me semblent pas essentielles) +# - sed -n : on convertit l'affichage de 12345 label en 'label'=12345 +# - sed smtpd : on rajoute le préfixe 'smtpd' aux labels idoines +# - sed km/000 : on multiplie par 1000/1000000 les valeurs suffixées par k ou m +# - tr : on met tout sur une même ligne +/usr/sbin/logtail2 -f "$LOG" -o "$LOGTAIL_OFFSET" \ +| /usr/sbin/pflogsumm -h 0 -u 0 --smtpd_stats --zero_fill \ +| head -n 30 \ +| sed 's/[[:space:]]*(.*).*//g' \ +| sed -n "s/^[[:space:]]*\([0-9]\+[kmg]\?\)[[:space:]]\+\([a-z \/\.]\+\).*/\'\2\'=\1/p" \ +| sed 's/\(connections\|hosts\/domains\|avg. connect time\)/smtpd \1/' \ +| sed -e 's/k$/000/' -e 's/m$/000000/' \ +| tr "\n" " " \ +>"$TMPFILE" + + +# Si la commande précédente s'est bien passée, on +# renvoie OK et les perfdata générées plus haut +if [ "$?" -eq "0" ] && [ -s "$TMPFILE" ]; then + printf "OK | " + cat "$TMPFILE" + printf "\n" +else + # Sinon, KO et warning (pas "critical", on est là juste pour des stats) + printf "KO \n" + EXIT_STATUS=1 +fi + +# Nettoyage du fichier temporaire +rm -f "$TMPFILE" + +# Petit accès de parano +chmod 600 "$LOGTAIL_OFFSET" + +exit $EXIT_STATUS diff --git a/nagios/check_postfix_postqueue.sh b/nagios/check_postfix_postqueue.sh new file mode 100755 index 0000000..4c3cf78 --- /dev/null +++ b/nagios/check_postfix_postqueue.sh @@ -0,0 +1,96 @@ +#!/bin/sh + +COMMANDE="/usr/sbin/postqueue -p" +WARNING_REQ=10 +CRITICAL_REQ=15 +WARNING_SIZE=20000000 +CRITICAL_SIZE=50000000 + + +# +# Fonction d'aide +# +usage() { + cat <{nodes}}) { + my $state = '-'; + my $conn; + my $status; + my $mem; + + eval { + $conn = PVE::ConfigClient::connect ($ticket, $cinfo, $ni->{cid}); + if ($status = $conn->ping()->result) { + $state = 'A'; + } + }; + + my $err = $@; + + if ($err) { + push(@listcrit, $ni->{cid} . ":(down)"); + } else { + $mem = int (0.5 + ($status->{meminfo}->{mbmemused}*100/$status->{meminfo}->{mbmemtotal})); + if ($mem >= $critical_level) { + push(@listcrit, $ni->{cid} . ":$mem"); + } else { + if ($mem >= $warning_level) { + push(@listwarn, $ni->{cid} . ":$mem"); + } else { + push(@listok, $ni->{cid} . ":$mem"); + } + } + + push (@listperfdata, $ni->{name} . "_mem=" + . $status->{meminfo}->{mbmemused} . "MB;" + . ($status->{meminfo}->{mbmemtotal} * $warning_level / 100) . ";" + . ($status->{meminfo}->{mbmemtotal} * $critical_level / 100) . ";" + . "0;" + . $status->{meminfo}->{mbmemtotal}); + } +} + +if (scalar(@listcrit) != 0) { + print "CRITICAL : " . join(", ", @listcrit); + $return_status = 2; +} else { + if (scalar(@listwarn) != 0) { + print "WARNING : " . join(", ", @listwarn); + $return_status = 1; + } else { + print "OK : " . join(", ", @listok); + } +} +print "|" . join(" ", @listperfdata) . "\n"; +exit $return_status; diff --git a/nagios/check_pve_mem_setuid.c b/nagios/check_pve_mem_setuid.c new file mode 100644 index 0000000..2f1d0e5 --- /dev/null +++ b/nagios/check_pve_mem_setuid.c @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +#define COMMAND_MAX_LENGTH 256 + +int main(int argc, char **argv) { + int warning_level = 80; + int critical_level = 90; + int help_needed = 0; + int opt; + char command[COMMAND_MAX_LENGTH]; + + /* Vérification du setuid root */ + if (setuid(0) != 0) { + perror("setuid root error.\n"); + exit(EXIT_FAILURE); + } + + /* Analyse des options */ + while ((opt = getopt (argc, argv, "w:c:")) != -1) { + switch (opt) + { + case 'w': + warning_level = atoi(optarg); + break; + + case 'c': + critical_level = atoi(optarg); + break; + + case '?': + help_needed = 1; + break; + } + } + + /* Lancement de la commande */ + if (help_needed != 0) { + return system("/usr/local/sbin/check_pve_mem.pl -h"); + } + if ( ! snprintf(command, COMMAND_MAX_LENGTH, "/usr/local/sbin/check_pve_mem.pl -w %d -c %d", warning_level, critical_level)) { + exit(EXIT_FAILURE); + } + exit(WEXITSTATUS(system(command))); +} diff --git a/nagios/check_quota.pl b/nagios/check_quota.pl new file mode 100644 index 0000000..4739303 --- /dev/null +++ b/nagios/check_quota.pl @@ -0,0 +1,90 @@ +#!/usr/bin/perl + +# TODO : intégrer avec utils.pm / Nagios::Plugin du CPAN +# TODO : gérer les niveaux via des arguments en ligne de commande + +use strict; +use Cyrus::IMAP::Shell; +use Data::Dumper; + + +my $configFile = '/root/.cyrus_auth'; +my $configWarningLevel = 90; +my $configCriticalLevel = 97; +my %cyrusConfig; + +my $var; +my $value; +my $username; +my $taux_occupation; +my @donnees; +my @quota; +my @listingMailboxes; + +my @listingWarning; +my @listingCritical; + +# Lecture du fichier de configuration +open CONFIG, $configFile; +while () { + chomp; # no newline + s/^#.*//; # no comments + s/^\s+//; # no leading white + s/\s+$//; # no trailing white + next unless length; # anything left? + my ($var, $value) = split(/\s*=\s*/, $_, 2); + $cyrusConfig{$var} = $value; +} + +# Connexion +my $conn = Cyrus::IMAP::Admin->new($cyrusConfig{'host'}) or die "Echec de connexion."; + +# Authentification +$conn->authenticate( + "-user" => $cyrusConfig{'user'}, + "-password" => $cyrusConfig{'password'}, + "-mechanism" => 'LOGIN', + ) or die "Echec à l'authentification."; + +# Boucle sur chacune des boîtes +@listingMailboxes = $conn->listmailbox('user.%'); +if ($conn->error) { + print $conn->error; + exit; +} +for (@listingMailboxes) { + # listingMailboxes est un tableau multi-dimensionnel + # On essaie de récupérer proprement les tableaux internes + @donnees = @$_; + $username = @donnees[0]; + + # Récupération du quota + @quota = $conn->listquota($username); + # fin de boucle si vide (= pas de quota) (ou erreur peut-être...) + next unless @quota; + if (shift(@quota) != 'STORAGE') { + die "Type de quota inconnu."; + } + + # Calcul du taux d'occupation et éventuel ajout aux + # listes warning/critical + $taux_occupation = 100 * $quota[0][0] / $quota[0][1]; + if ( $taux_occupation > $configCriticalLevel ) { + push (@listingCritical, $username . sprintf("(%.4f)", $taux_occupation)); + } else { + if ( $taux_occupation > $configWarningLevel ) { + push (@listingWarning, $username . sprintf("(%.4f)", $taux_occupation)); + } + } +} + +if (@listingCritical) { + print "CRITICAL : " . scalar(@listingCritical) . " au dessus de " . $configCriticalLevel . "% : " . join ", ", @listingCritical; + exit(2); +} +if (@listingWarning) { + print "WARNING : " . scalar(@listingWarning) . " au dessus de " . $configWarningLevel . "% : " . join ", ", @listingWarning; + exit(1); +} +print "OK"; +exit(0); diff --git a/nagios/check_rbl b/nagios/check_rbl new file mode 100644 index 0000000..0bca191 --- /dev/null +++ b/nagios/check_rbl @@ -0,0 +1,618 @@ +#!perl + +# nagios: -epn + +package main; + +# check_rbl is a Nagios plugin to check if an SMTP server is black- or +# white- listed +# +# See the INSTALL file for installation instructions +# +# Copyright (c) 2014, Matteo Corti +# Copyright (c) 2007, ETH Zurich. +# Copyright (c) 2010, Elan Ruusamae . +# +# This module is free software; you can redistribute it and/or modify it +# under the terms of GNU general public license (gpl) version 3. +# See the LICENSE file for details. + +use strict; +use warnings; + +use 5.00800; + +our $VERSION = '1.3.8'; + +use Data::Validate::Domain qw(is_hostname); +use Data::Validate::IP qw(is_ipv4 is_ipv6); +use IO::Select; +use Net::DNS; +use Readonly; +use English qw(-no_match_vars); +use Data::Dumper; + +my $plugin_module = load_module( 'Monitoring::Plugin', 'Nagios::Plugin' ); +my $plugin_threshold_module = + load_module( 'Monitoring::Plugin::Threshold', 'Nagios::Plugin::Threshold' ); +my $plugin_getopt_module = + load_module( 'Monitoring::Plugin::Getopt', 'Nagios::Plugin::Getopt' ); + +# Check which version of the monitoring plugins is available + +sub load_module { + + my @names = @_; + my $loaded_module; + + for my $name (@names) { + + my $file = $name; + + # requires need either a bare word or a file name + $file =~ s{::}{/}gsxm; + $file .= '.pm'; + + eval { ## no critic (ErrorHandling::RequireCheckingReturnValueOfEval) + require $file; + $name->import(); + }; + if ( !$EVAL_ERROR ) { + $loaded_module = $name; + last; + } + } + + if ( !$loaded_module ) { + #<<< + print 'CHECK_RBL: plugin not found: ' . join( ', ', @names ) . "\n"; ## no critic (RequireCheckedSyscall) + #>>> + + exit 2; + } + + return $loaded_module; + +} + +Readonly our $DEFAULT_TIMEOUT => 15; +Readonly our $DEFAULT_RETRIES => 4; +Readonly our $DEFAULT_WORKERS => 20; +Readonly our $DEFAULT_QUERY_TIMEOUT => 15; + +# IMPORTANT: Nagios plugins could be executed using embedded perl in this case +# the main routine would be executed as a subroutine and all the +# declared subroutines would therefore be inner subroutines +# This will cause all the global lexical variables not to stay shared +# in the subroutines! +# +# All variables are therefore declared as package variables... +# + +## no critic (ProhibitPackageVars) +our ( @listed, @timeouts, $options, $plugin, $threshold, $timeouts_string, ); + +############################################################################## +# Usage : debug("some message string") +# Purpose : write a message if the debugging option was specified +# Returns : n/a +# Arguments : message : message string +# Throws : n/a +# Comments : n/a +# See also : n/a +sub debug { + + # arguments + my $message = shift; + + if ( !defined $message ) { + $plugin->nagios_exit( $plugin_module->UNKNOWN, + q{Internal error: not enough parameters for 'debug'} ); + } + + if ( $options && $options->debug() ) { + ## no critic (RequireCheckedSyscall) + print "[DBG] $message\n"; + } + + return; + +} + +############################################################################## +# Usage : verbose("some message string", $optional_verbosity_level); +# Purpose : write a message if the verbosity level is high enough +# Returns : n/a +# Arguments : message : message string +# level : options verbosity level +# Throws : n/a +# Comments : n/a +# See also : n/a +sub verbose { + + # arguments + my $message = shift; + my $level = shift; + + if ( !defined $message ) { + $plugin->nagios_exit( $plugin_module->UNKNOWN, + q{Internal error: not enough parameters for 'verbose'} ); + } + + if ( !defined $level ) { + $level = 0; + } + + if ( $level < $options->verbose ) { + if ( !print $message ) { + $plugin->nagios_exit( $plugin_module->UNKNOWN, + 'Error: cannot write to STDOUT' ); + } + } + + return; + +} + +# the script is declared as a package so that it can be unit tested +# but it should not be used as a module +if ( !caller ) { + run(); +} + +############################################################################## +# Usage : my $res = init_dns_resolver( $retries ) +# Purpose : Initializes a new DNS resolver +# Arguments : retries : number of retries +# Returns : The newly created resolver +# See also : Perl Net::DNS +sub init_dns_resolver { + + my $retries = shift; + + my $res = Net::DNS::Resolver->new(); + if ( $res->can('force_v4') ) { + $res->force_v4(1); + } + + if ($retries) { + $res->retry($retries); + } + + return $res; +} + +############################################################################## +# Usage : mdns(\@addresses, $callback) +# Purpose : Perform multiple DNS lookups in parallel +# Returns : n/a +# See also : Perl Net::DNS module mresolv in examples +# +# Resolves all IPs in C<@addresses> in parallel. +# If answer is found C<$callback> is called with arguments as: $name, $host. +# +# Author: Elan Ruusamae , (c) 1999-2010 +sub mdns { + + my ( $data, $callback ) = @_; + + # number of requests to have outstanding at any time + my $workers = $options ? $options->workers() : 1; + + # timeout per query (seconds) + my $timeout = $options ? $options->get('query-timeout') : $DEFAULT_TIMEOUT; + my $res = init_dns_resolver( $options ? $options->retry() : 0 ); + + my $sel = IO::Select->new(); + my $eof = 0; + + my @addrs = @{$data}; + + my %addrs; + while (1) { + + #---------------------------------------------------------------------- + # Read names until we've filled our quota of outstanding requests. + #---------------------------------------------------------------------- + + while ( !$eof && $sel->count() < $workers ) { + + my $name = shift @addrs; + + if ( !defined $name ) { + debug('reading...EOF.'); + $eof = 1; + last; + } + + debug("reading...$name"); + + my $sock = $res->bgsend($name); + + if ( !defined $sock ) { + verbose 'DNS query error: ' . $res->errorstring; + verbose "Skipping $name"; + } + else { + + # we store in a hash the query we made, as parsing it back from + # response gives different ip for ips with multiple hosts + $addrs{$sock} = $name; + $sel->add($sock); + debug( "name = $name, outstanding = " . $sel->count() ); + + } + + } + + #---------------------------------------------------------------------- + # Wait for any replies. Remove any replies from the outstanding pool. + #---------------------------------------------------------------------- + + my @ready; + my $timed_out = 1; + + debug('waiting for replies'); + + @ready = $sel->can_read($timeout); + + while (@ready) { + + $timed_out = 0; + + debug( 'replies received: ' . scalar @ready ); + + foreach my $sock (@ready) { + + debug('handling a reply'); + + my $addr = $addrs{$sock}; + delete $addrs{$sock}; + $sel->remove($sock); + + my $ans = $res->bgread($sock); + + debug Dumper $ans; + + my $host; + + if ($ans) { + + foreach my $rr ( $ans->answer ) { + + debug('Processing answer'); + + ## no critic(ProhibitDeepNests) + if ( !( $rr->type eq 'A' ) ) { + next; + } + + $host = $rr->address; + + debug("host = $host"); + + # take just the first answer + last; + } + } + else { + + debug( 'no answer: ' . $res->errorstring() ); + + } + + if ( defined $host ) { + + debug("callback( $addr, $host )"); + + } + else { + + debug("callback( $addr, )"); + + } + + &{$callback}( $addr, $host ); + } + + @ready = $sel->can_read(0); + + } + + #---------------------------------------------------------------------- + # If we timed out waiting for replies, remove all entries from the + # outstanding pool. + #---------------------------------------------------------------------- + + if ($timed_out) { + + debug('timeout: clearing the outstanding pool.'); + + foreach my $sock ( $sel->handles() ) { + my $addr = $addrs{$sock}; + delete $addrs{$sock}; + $sel->remove($sock); + + # callback for hosts that timed out + &{$callback}( $addr, q{} ); + } + } + + debug( 'outstanding = ' . $sel->count() . ", eof = $eof" ); + + #---------------------------------------------------------------------- + # We're done if there are no outstanding queries and we've read EOF. + #---------------------------------------------------------------------- + + last if ( $sel->count() == 0 ) && $eof; + } + + return; + +} + +############################################################################## +# Usage : validate( $hostname ); +# Purpose : check if an IP address or host name is valid +# Returns : the IP address corresponding to $hostname +# Arguments : n/a +# Throws : an UNKNOWN error if the argument is not valid +# Comments : n/a +# See also : n/a +sub validate { + + my $hostname = shift; + my $ip = $hostname; + + debug("validate($hostname, $ip)"); + + if ( !is_ipv4($hostname) && !is_ipv6($hostname) ) { + + if ( is_hostname($hostname) ) { + + mdns( + [$hostname], + sub { + my ( $addr, $host ) = @_; + $ip = $host; + } + ); + + if ( !$ip ) { + $plugin->nagios_exit( $plugin_module->UNKNOWN, + 'Cannot resolve ' . $hostname ); + } + + } + + if ( !$ip ) { + $plugin->nagios_exit( $plugin_module->UNKNOWN, + 'Cannot resolve ' . $options->host ); + } + + } + + return $ip; + +} + +############################################################################## +# Usage : run(); +# Purpose : main method +# Returns : n/a +# Arguments : n/a +# Throws : n/a +# Comments : n/a +# See also : n/a +sub run { + + ################################################################################ + # Initialization + + $plugin = $plugin_module->new( shortname => 'CHECK_RBL' ); + + my $time = time; + + ######################## + # Command line arguments + + $options = $plugin_getopt_module->new( + usage => 'Usage: %s [OPTIONS]', + version => $VERSION, + url => 'http://matteocorti.github.io/check_rbl/', + blurb => 'Check SMTP black- or white- listing status', + ); + + $options->arg( + spec => 'critical|c=i', + help => 'Number of blacklisting servers for a critical warning', + required => 0, + default => 1, + ); + + $options->arg( + spec => 'warning|w=i', + help => 'Number of blacklisting servers for a warning', + required => 0, + default => 1, + ); + + $options->arg( + spec => 'debug|d', + help => 'Prints debugging information', + required => 0, + default => 0, + ); + + $options->arg( + spec => 'server|s=s@', + help => 'RBL server', + required => 1, + ); + + $options->arg( + spec => 'host|H=s', + help => 'SMTP server to check', + required => 1, + ); + + $options->arg( + spec => 'retry|r=i', + help => 'Number of times to try a DNS query (default is 4) ', + required => 0, + default => $DEFAULT_RETRIES, + ); + + $options->arg( + spec => 'workers=i', + help => 'Number of parallel checks', + required => 0, + default => $DEFAULT_WORKERS, + ); + + $options->arg( + spec => 'whitelistings|wl', + help => 'Check whitelistings instead of blacklistings', + required => 0, + default => 0, + ); + + $options->arg( + spec => 'query-timeout=i', + help => 'Timeout of the RBL queries', + required => 0, + default => $DEFAULT_QUERY_TIMEOUT, + ); + + $options->getopts(); + + ############### + # Sanity checks + + if ( $options->critical < $options->warning ) { + $plugin->nagios_exit( $plugin_module->UNKNOWN, + 'critical has to be greater or equal warning' ); + } + + my $ip = validate( $options->host ); + + my @servers = @{ $options->server }; + + verbose 'Using ' . $options->timeout . " as global script timeout\n"; + alarm $options->timeout; + + ################ + # Set the limits + + # see https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT + $threshold = $plugin_threshold_module->set_thresholds( + warning => $options->warning - 1, + critical => $options->critical - 1, + ); + + ################################################################################ + + my $nservers = scalar @servers; + + verbose 'Checking ' . $options->host . " ($ip) on $nservers server(s)\n"; + + # build address lists + my @addrs; + foreach my $server (@servers) { + ( my $local_ip = $ip ) =~ +s/(\d{1,3}) [.] (\d{1,3}) [.] (\d{1,3}) [.] (\d{1,3})/$4.$3.$2.$1.$server/mxs; + push @addrs, $local_ip; + } + + mdns( + \@addrs, + sub { + my ( $addr, $host ) = @_; + + if ( defined $host ) { + + debug("callback( $addr, $host )"); + + } + else { + + debug("callback( $addr, )"); + + } + + # extract RBL we checked + $addr =~ s/^(?:\d+[.]){4}//mxs; + if ( defined $host ) { + if ( $host eq q{} ) { + push @timeouts, $addr; + } + else { + verbose "listed in $addr as $host\n"; + if ( !$options->get('whitelistings') ) { + push @listed, $addr; + } + } + } + else { + verbose "not listed in $addr\n"; + if ( $options->get('whitelistings') ) { + push @listed, $addr; + } + } + } + ); + + my $total = scalar @listed; + + my $status; + if ( $options->get('whitelistings') ) { + + $status = + $options->host + . " NOT WHITELISTED on $total " + . ( ( $total == 1 ) ? 'server' : 'servers' ) + . " of $nservers"; + } + else { + $status = + $options->host + . " BLACKLISTED on $total " + . ( ( $total == 1 ) ? 'server' : 'servers' ) + . " of $nservers"; + + } + + # append timeout info, but do not account these in status + if (@timeouts) { + $timeouts_string = scalar @timeouts; + $status = + " ($timeouts_string server" + . ( ( $timeouts_string > 1 ) ? 's' : q{} ) + . ' timed out: ' + . join( ', ', @timeouts ) . ')'; + } + + if ( $total > 0 ) { + $status .= " (@listed)"; + } + + $plugin->add_perfdata( + label => 'servers', + value => $total, + uom => q{}, + threshold => $threshold, + ); + + $plugin->add_perfdata( + label => 'time', + value => time - $time, + uom => q{s}, + ); + + $plugin->nagios_exit( $threshold->get_status($total), $status ); + + return; + +} + +1; diff --git a/nagios/check_sendmail-mailstats.sh b/nagios/check_sendmail-mailstats.sh new file mode 100755 index 0000000..4c682e7 --- /dev/null +++ b/nagios/check_sendmail-mailstats.sh @@ -0,0 +1,50 @@ +#!/bin/sh + +# Little Nagios check to save the Sendmail mailstats + +CATEGORY="" +OUTPUT_PERFDATA="" + +# Stop at the first non-catched error +set -e + +# We use the "idiom" suggested by http://www.etalabs.net/sh_tricks.html +# based on "done </dev/null) +EOF + +# if not all data is present, we return an unknown status +# (remove this block if you don't mind) +if ! echo "$OUTPUT_PERFDATA" | grep "MTA_msg" >/dev/null 2>&1 \ + || ! echo "$OUTPUT_PERFDATA" | grep "MSP_msg" >/dev/null 2>&1 \ + || ! echo "$OUTPUT_PERFDATA" | grep "MTA_tcp" >/dev/null 2>&1 \ + || ! echo "$OUTPUT_PERFDATA" | grep "MSP_tcp" >/dev/null 2>&1 \ + ; then + echo "UNKNOWN" + exit 3 +fi + +# Remove starting space to OUTPUT_PERFDATA +printf "OK|%s\n" "$( echo $OUTPUT_PERFDATA )" diff --git a/nagios/check_sendmail_queue.sh b/nagios/check_sendmail_queue.sh new file mode 100755 index 0000000..73ccd02 --- /dev/null +++ b/nagios/check_sendmail_queue.sh @@ -0,0 +1,96 @@ +#!/bin/sh + +# Replace COMMANDE by mailq if you want both new and old messages listed +COMMANDE="/usr/sbin/sendmail -bp" +WARNING_REQ=10 +CRITICAL_REQ=15 +WARNING_SIZE=20000000 +CRITICAL_SIZE=50000000 + + +# +# Fonction d'aide +# +usage() { + cat </dev/null 2>&1 + if [ "$?" -eq "2" ]; then + return 1 + fi + return 0 +} + +# Some early checks +if ! which $SHINKEN_ARBITER_PATH >/dev/null 2>&1 ; then + echo "UNKNOWN 'shinken-arbiter' not found in path : $PATH" + exit $STATE_UNKNOWN +fi + +# Get the values +LISTING="$( $SHINKEN_ARBITER_PATH $SHINKEN_ARBITER_OPTIONS | sed -n 's/^\tChecked \([0-9]\+\) \(.\+\)$/\2\t\1/p' | sort )" +OUTPUT_PERFDATA_REMNANT="$( printf "%s" "$LISTING" | sed 's/\t/=/g' | tr '\n' ' ' )" + +# +# Gestion des paramètres +# +while getopts hw:c:t: f; do + case "$f" in + 'h') + usage + exit + ;; + + 'w') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_WARNING="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 'c') + if check_range_syntax "$OPTARG" >/dev/null; then + RANGE_CRITICAL="$OPTARG" + else + echo "UNKNOWN: invalid range." + exit 3 + fi + ;; + + 't') + # Ce n'est pas très propre, mais on gère tout ici plutôt que de remplir + # un buffer et de le traiter ensuite + CATEGORY="$OPTARG" + CPT=$( printf "%s\n" "$LISTING" | grep -- "^$CATEGORY[[:space:]]" | cut -f 2 ) + + if [ -z "$CPT" ]; then + printf "UNKNOWN: unknown category $CATEGORY" + exit $STATE_UNKNOWN + fi + + # mémo : 'label'=value[UOM];[warn];[crit];[min];[max] + OUTPUT_PERFDATA=$( printf "%s'%s'=%d;%s;%s;0;" \ + "$( test -n "$OUTPUT_PERFDATA" && echo "$OUTPUT_PERFDATA " )" \ + "$CATEGORY" \ + "$CPT" \ + "$RANGE_WARNING" \ + "$RANGE_CRITICAL" ) + + # We remove the item from the "remnants" + OUTPUT_PERFDATA_REMNANT="$( printf "%s" "$OUTPUT_PERFDATA_REMNANT" | sed "s/[[:space:]]*$CATEGORY=[0-9]\+[[:space:]]*/ /" )" + + # Check value against critical & warning range + if check_range "$CPT" "$RANGE_CRITICAL"; then + OUTPUT_EXIT_STATUS=$STATE_CRITICAL + OUTPUT_DETAIL_CRITICAL="$OUTPUT_DETAIL_CRITICAL Cat:$CATEGORY($CPT)" + elif check_range "$CPT" "$RANGE_WARNING"; then + if [ "$OUTPUT_EXIT_STATUS" -eq 0 ]; then + OUTPUT_EXIT_STATUS=$STATE_WARNING + fi + OUTPUT_DETAIL_WARNING="$OUTPUT_DETAIL_WARNING Cat:$CATEGORY($CPT)" + fi + ;; + + \?) + usage + exit 1 + ;; + esac +done + +OUTPUT_PERFDATA="$OUTPUT_PERFDATA $OUTPUT_PERFDATA_REMNANT" + +case "$OUTPUT_EXIT_STATUS" in + "$STATE_OK") + printf "OK" + ;; + "$STATE_WARNING") + printf "WARNING %s" "$OUTPUT_DETAIL_WARNING" + ;; + "$STATE_CRITICAL") + printf "CRITICAL %s" "$OUTPUT_DETAIL_CRITICAL" + ;; + *) + printf "UNKNOWN" + ;; +esac + +printf "|%s\n" "$OUTPUT_PERFDATA" +# on supprime les retours à la ligne +exit $OUTPUT_EXIT_STATUS diff --git a/nagios/check_temperature.sh b/nagios/check_temperature.sh new file mode 100755 index 0000000..1562772 --- /dev/null +++ b/nagios/check_temperature.sh @@ -0,0 +1,99 @@ +#!/bin/sh + +# Petit script custom pour relever la température des processeurs +# +# On ne tient pas compte des indications "high" et "critical" émises +# par sensors, mais seulement de celles fournies en argument comme +# seuils "warning" et "critical" + +# Config par défaut +WARNING_LEVEL=60 +CRITICAL_LEVEL=80 + +# +# Fonction d'aide +# +usage() { + cat </dev/null 2>&1 ; then + echo "UNKNOWN 'sensors' not found." + exit 1 +fi + +# On lance la commande +# note: on tronque les flottants en entiers. +DATA=$( /usr/bin/sensors | sed -n "s/^\([A-Za-z0-9 ]\+\):[[:space:]]*+\?\(-\?[0-9]\+\)\.\?[0-9]*.C.*$/'\1'=\2;$WARNING_LEVEL;$CRITICAL_LEVEL;;/p" ) +if [ -z "$DATA" ]; then + echo "UNKNOWN no cpu found" + exit 3 +fi + +# ...puis on lance la boucle principale +# note: en faisant sensors | while read line; on entre dans un sous-process shell et les variables deviennent donc locales. +# D'où cette bidouille à base de redirection. +# TODO: tester la portabilité (bash ok, dash ok) +RETURN_STATUS=0 +RETURN_COMMENT="OK" +while read LINE; do + TEMPERATURE="$( echo $LINE | sed 's/.*=\([0-9]\+\);.*/\1/' )" + SONDE="$( echo $LINE | sed "s/^'\([^']\+\)'=.*/\1/" )" + # Si la température est au-dessus du niveau critique, et que la sonde + # ne fait pas partie des exclues => alerte + if [ "$TEMPERATURE" -gt "$CRITICAL_LEVEL" ] && ! echo "$EXCLUSIONS" | grep "^$SONDE$" >/dev/null; then + RETURN_STATUS=2 + RETURN_COMMENT="CRITICAL" + fi + # Idem ci-dessus + vérification que l'on n'a pas déjà levé une alerte + # (si c'était le cas, on serait déjà en Warning, voir en critical) + if [ "$TEMPERATURE" -gt "$WARNING_LEVEL" ] && [ "$RETURN_STATUS" -eq "0" ] && ! echo "$EXCLUSIONS" | grep "^$SONDE$" >/dev/null; then + RETURN_STATUS=1 + RETURN_COMMENT="WARNING" + fi +done </dev/null 2>&1; then + echo "UNKNOWN: 'whois' command not found." + exit 1 +fi + + +# +# Parameters management +# +while [ "$#" -gt 0 ]; do + while getopts hw:c: f; do + case "$f" in + 'h') + usage + exit + ;; + + 'w') + THRESHOLD_WARNING="$( convert_to_seconds "$OPTARG" )" + ;; + + 'c') + THRESHOLD_CRITICAL="$( convert_to_seconds "$OPTARG" )" + ;; + + \?) + usage + exit 1 + ;; + esac + done + shift $( expr $OPTIND - 1 ) + + # Little checks + if ! is_int "$THRESHOLD_WARNING" || ! is_int "$THRESHOLD_CRITICAL"; then + echo "UNKNOWN invalid parameter : one of the threshold is not an integer." + exit $STATE_UNKNOWN + fi + + # End of the options, we get the domain name + if [ -z "$1" ]; then + # No more options but no domain specified ? Weird but well... + break + fi + DOMAIN="$1" + shift + + # get the expiration date for this domain + EXPIRATION_DATE="$( whois "$DOMAIN" | extract_date_from_whois )" + if [ -z "$EXPIRATION_DATE" ]; then + # We couldn't get the date :-( + if [ "$OUTPUT_EXIT_STATUS" -eq "$STATE_OK" ]; then + OUTPUT_EXIT_STATUS="$STATE_UNKNOWN" + fi + OUTPUT_DETAIL_UNKNOWN="$OUTPUT_DETAIL_UNKNOWN $DOMAIN:could_not_get_date" + break + fi + + # Dispatch in the OK/Warning/Critical boxes + OUTPUT_DOMAIN_DETAIL="$DOMAIN:$( date --date=@$EXPIRATION_DATE +%FT%T%z)" + if [ "$EXPIRATION_DATE" -le "$( expr "$TIMESTAMP_NOW" + "$THRESHOLD_CRITICAL" )" ]; then + # Domain is critical + OUTPUT_EXIT_STATUS="$STATE_CRITICAL" + OUTPUT_DETAIL_CRITICAL="$OUTPUT_DETAIL_CRITICAL $OUTPUT_DOMAIN_DETAIL" + elif [ "$EXPIRATION_DATE" -le "$( expr "$TIMESTAMP_NOW" + "$THRESHOLD_WARNING" )" ]; then + # Domain is warning + OUTPUT_DETAIL_WARNING="$OUTPUT_DETAIL_WARNING $OUTPUT_DOMAIN_DETAIL" + # we don't change if the status is already Critical + # (but we take precedence over Unknown) + if [ "$OUTPUT_EXIT_STATUS" -ne "$STATE_CRITICAL" ]; then + OUTPUT_EXIT_STATUS="$STATE_WARNING" + fi + else + # Domain is Ok + OUTPUT_DETAIL_OK="$OUTPUT_DETAIL_OK $OUTPUT_DOMAIN_DETAIL" + fi +done + +# final output +case "$OUTPUT_EXIT_STATUS" in + "$STATE_OK") + echo "OK $OUTPUT_DETAIL_OK" + ;; + + "$STATE_WARNING") + echo "WARNING $OUTPUT_DETAIL_WARNING" + ;; + + "$STATE_CRITICAL") + echo "CRITICAL $OUTPUT_DETAIL_CRITICAL" + ;; + + "$STATE_UNKNOWN") + echo "UNKNOWN $OUTPUT_DETAIL_UNKNOWN" + ;; + + *) + echo "WTF" + ;; +esac + +exit "$OUTPUT_EXIT_STATUS" diff --git a/nagios/check_wp.php b/nagios/check_wp.php new file mode 100644 index 0000000..169dbea --- /dev/null +++ b/nagios/check_wp.php @@ -0,0 +1,244 @@ +#!/usr/bin/php +]*generator[^>]*wordpress\s+([0-9.]+)/i', $data, $matches); + if (count ($matches) < 2 || !$matches[1]) + { + echo "no version in web found...\n"; + exit (WRN); + } + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, "http://api.wordpress.org/core/version-check/1.2/?version=" . $matches[1]); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_NOSIGNAL, 1); + $data = curl_exec($ch); + curl_close($ch); + + $data = explode ("\n", $data); + if (version_compare ($data[3], $matches[1]) > 0) + { + echo "Your core is out of date! " . $matches[1] . " -> " . $data[3] . "\n"; + exit (ERR); + } + + // that's it + echo "Running " . $matches[1] . " is fine.\n"; + exit (OOK); +} + + +// ok lets check a local installation! + +if ($domain) // multihost + $_SERVER['HTTP_HOST'] = $domain; + +// include wp stuff, don't need to to reinvent the wheel... +require_once($instdir.'/wp-load.php'); + +// let wordpress prepare it's tests +wp_version_check(); +wp_update_plugins(); +wp_update_themes(); + +// if it's pre 2.9 get_site_transient might be missing... pretty old my friend! +if (!function_exists ("get_site_transient")) +{ + echo "OMG. Time to get some updates!!!"; + exit (ERR); +} + +$ret = OOK; +$suppl = ""; +$msg = array (); + +// check the core of your wordpress +if ($check_core) +{ + $core = get_site_transient('update_core'); + if (isset ($core->updates) && version_compare ($core->updates[0]->current, $core->version_checked) > 0) + { + $msg[] = "Core is out-of-date!"; + $suppl .= "Core: " . $core->version_checked . " -> " . $core->updates[0]->current . "; "; + $ret = max ($ret, ERR); + } + else + $msg[] = "Core is up-to-date."; +} +else + $msg[] = "Skipping core checks!"; + +// check the plugins +if ($check_plugins) +{ + $plugin_msg = array (); + $plugins = get_site_transient('update_plugins'); + if (isset ($plugins->response)) + { + foreach($plugins->response as $name => $update) + { + $plugin_msg[] = $update->slug . ": " . $plugins->checked[$name] ." -> " . $update->new_version; + } + } + if (count ($plugin_msg)) + { + $s = "s are"; + if (count ($plugin_msg) == 1) + $s = " is"; + $msg[] = count ($plugin_msg) . " plugin" . $s . " out-of-date!"; + $suppl .= implode ("; ", $plugin_msg) . "; "; + $ret = max ($ret, ERR); + } + else + $msg[] = "Plugins are up-to-date."; +} +else + $msg[] = "Skipping plugin checks!"; + +// check the themes +if ($check_themes) +{ + $themes_msg = array (); + $themes = get_site_transient('update_themes'); + if (isset ($themes->response)) + { + foreach($themes->response as $name => $update) + { + $themes_msg[] = $name . ": " . $themes->checked[$name] ." -> " . $update["new_version"]; + } + } + if (count ($themes_msg)) + { + $s = "s are"; + if (count ($plugin_msg) == 1) + $s = " is"; + $msg[] = count ($themes_msg) . " theme" . $s . " out-of-date!"; + $suppl .= implode ("; ", $themes_msg) . "; "; + $ret = max ($ret, ERR); + } + else + $msg[] = "Themes are up-to-date."; +} +else + $msg[] = "Skipping theme checks!"; + +// Get the perfdata +$count_posts = wp_count_posts(); +$perfdata['posts_published'] = sprintf('%s=%s', 'posts_published', $count_posts->publish); +$comments_count = wp_count_comments(); +$perfdata['comments'] = sprintf('%s=%s', 'comments', $comments_count->total_comments); +$count_users = count_users(); +$perfdata['users'] = sprintf('%s=%s', 'users', $count_users['total_users']); + +// collect our info +if ($ret == OOK) + echo "Well done! "; +else + echo "Need attention! "; + +echo implode (" - ", $msg) . " - " . $suppl . "|" . implode(' ', $perfdata) . "\n"; +exit ($ret); + diff --git a/nagios/check_zone_rrsig_expiration b/nagios/check_zone_rrsig_expiration new file mode 100755 index 0000000..bed0455 --- /dev/null +++ b/nagios/check_zone_rrsig_expiration @@ -0,0 +1,313 @@ +#!/usr/bin/perl + +# $Id: check_zone_rrsig_expiration,v 1.14 2015/10/12 16:54:20 wessels Exp $ +# +# check_zone_rrsig_expiration +# +# nagios plugin to check expiration times of RRSIG records. Reminds +# you if its time to re-sign your zone. + +# Copyright (c) 2008, The Measurement Factory, Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# Neither the name of The Measurement Factory nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +# usage +# +# define command { +# command_name check-zone-rrsig +# command_line /usr/local/libexec/nagios-local/check_zone_rrsig -Z $HOSTADDRESS$ +# } +# +# define service { +# name dns-rrsig-service +# check_command check-zone-rrsig +# ... +# } +# +# define host { +# use dns-zone +# host_name zone.example.com +# alias ZONE example.com +# } +# +# define service { +# use dns-rrsig-service +# host_name zone.example.com +# } + +use warnings; +use strict; + +use Getopt::Std; +use Net::DNS::Resolver; +use Time::HiRes qw ( gettimeofday tv_interval); +use Time::Local; +use List::Util qw ( shuffle ); + +# options +# -Z zone Zone to test +# -t seconds DNS query timeout +# -d debug +# -C days Critical if expiring in this many days +# -W days Warning if expiring in this many days +# -T type Query type (default SOA) +# -4 use IPv4 only +# -U size EDNS0 UDP packet size (default 4096) +my %opts = (t=>30, C=>2, W=>3, T=>'SOA', U=>4096); +getopts('4Z:dt:W:C:T:U:', \%opts); +usage() unless $opts{Z}; +usage() if $opts{h}; +my $zone = $opts{Z}; +$zone =~ s/^zone\.//; + +my $data; +my $start; +my $stop; + +my @refs = qw ( +a.root-servers.net +b.root-servers.net +c.root-servers.net +d.root-servers.net +e.root-servers.net +f.root-servers.net +g.root-servers.net +h.root-servers.net +i.root-servers.net +j.root-servers.net +k.root-servers.net +l.root-servers.net +m.root-servers.net +); + +$start = [gettimeofday()]; +do_recursion(); +do_queries(); +$stop = [gettimeofday()]; +do_analyze(); + +sub do_recursion { + my $done = 0; + my $res = Net::DNS::Resolver->new; + do { + print STDERR "\nRECURSE\n" if $opts{d}; + my $pkt; + foreach my $ns (shuffle @refs) { + print STDERR "sending query for $zone $opts{T} to $ns\n" if $opts{d}; + $res->nameserver($ns); + $res->udp_timeout($opts{t}); + $res->recurse(0); + $res->dnssec(1); + $res->udppacketsize($opts{U}); + $res->force_v4(1) if $opts{'4'}; + $pkt = $res->send($zone, $opts{T}); + last if $pkt; + } + critical("No response to seed query") unless $pkt; + critical($pkt->header->rcode . " from " . $pkt->answerfrom) + unless ($pkt->header->rcode eq 'NOERROR'); + @refs = (); + foreach my $rr ($pkt->authority) { + next unless $rr->type eq 'NS'; + print STDERR $rr->string, "\n" if $opts{d}; + push (@refs, $rr->nsdname); + next unless names_equal($rr->name, $zone); + add_nslist_to_data($pkt); + $done = 1; + } + } while (! $done); +} + + +sub do_queries { + my $n; + do { + $n = 0; + foreach my $ns (keys %$data) { + next if $data->{$ns}->{done}; + print STDERR "\nQUERY $ns\n" if $opts{d}; + + my $pkt = send_query($zone, $opts{T}, $ns); + add_nslist_to_data($pkt); + $data->{$ns}->{queries}->{$opts{T}} = $pkt; + + print STDERR "done with $ns\n" if $opts{d}; + $data->{$ns}->{done} = 1; + $n++; + } + } while ($n); +} + +sub do_analyze { + my $nscount = 0; + my $NOW = time; + my %MAX_EXP_BY_TYPE; + foreach my $ns (keys %$data) { + print STDERR "\nANALYZE $ns\n" if $opts{d}; + my $pkt = $data->{$ns}->{queries}->{$opts{T}}; + critical("No response from $ns") unless $pkt; + print STDERR $pkt->string if $opts{d}; + critical($pkt->header->rcode . " from $ns") + unless ($pkt->header->rcode eq 'NOERROR'); + critical("$ns is lame") unless $pkt->header->ancount; + foreach my $rr ($pkt->answer) { + next unless $rr->type eq 'RRSIG'; + my $exp = sigrr_exp_epoch($rr); + my $T = $rr->typecovered; + if (!defined($MAX_EXP_BY_TYPE{$T}->{exp}) || $exp > $MAX_EXP_BY_TYPE{$T}->{exp}) { + $MAX_EXP_BY_TYPE{$T}->{exp} = $exp; + $MAX_EXP_BY_TYPE{$T}->{ns} = $ns; + } + } + $nscount++; + } + warning("No nameservers found. Is '$zone' a zone?") if ($nscount < 1); + warning("No RRSIGs found") unless %MAX_EXP_BY_TYPE; + my $min_exp = undef; + my $min_ns = undef; + my $min_type = undef; + foreach my $T (keys %MAX_EXP_BY_TYPE) { + printf STDERR ("%s RRSIG expires in %.1f days\n", $T, ($MAX_EXP_BY_TYPE{$T}->{exp}-$NOW)/86400) if $opts{d}; + if (!defined($min_exp) || $MAX_EXP_BY_TYPE{$T}->{exp} < $min_exp) { + $min_exp = $MAX_EXP_BY_TYPE{$T}->{exp}; + $min_ns = $MAX_EXP_BY_TYPE{$T}->{ns}; + $min_type = $T; + } + } + critical("$min_ns has expired RRSIGs") if ($min_exp < $NOW); + if ($min_exp - $NOW < ($opts{C}*86400)) { + my $ND = sprintf "%3.1f days", ($min_exp-$NOW)/86400; + critical("$min_type RRSIG expires in $ND at $min_ns") + } + if ($min_exp - $NOW < ($opts{W}*86400)) { + my $ND = sprintf "%3.1f days", ($min_exp-$NOW)/86400; + warning("$min_type RRSIG expires in $ND at $min_ns") + } + success("No RRSIGs expiring in the next $opts{W} days"); +} + +sub sigrr_exp_epoch { + my $rr = shift; + die unless $rr->type eq 'RRSIG'; + my $exp = $rr->sigexpiration; + die "bad exp time '$exp'" + unless $exp =~ /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/; + my $exp_epoch = timegm($6,$5,$4,$3,$2-1,$1); + return $exp_epoch; +} + +sub add_nslist_to_data { + my $pkt = shift; + foreach my $ns (get_nslist($pkt)) { + next if defined $data->{$ns}->{done}; + print STDERR "adding NS $ns\n" if $opts{d}; + $data->{$ns}->{done} |= 0; + } +} + +sub success { + output('OK', shift); + exit(0); +} + +sub warning { + output('WARNING', shift); + exit(1); +} + +sub critical { + output('CRITICAL', shift); + exit(2); +} + +sub output { + my $state = shift; + my $msg = shift; + $stop = [gettimeofday()] unless $stop; + my $latency = tv_interval($start, $stop); + printf "ZONE %s: %s; (%.2fs) |time=%.6fs;;;0.000000\n", + $state, + $msg, + $latency, + $latency; +} + +sub usage { + print STDERR "usage: $0 -Z zone -d -t timeout -W days -C days\n"; + print STDERR "\t-Z zone zone to test\n"; + print STDERR "\t-T type query type (default SOA)\n"; + print STDERR "\t-d debug\n"; + print STDERR "\t-t seconds timeout on DNS queries\n"; + print STDERR "\t-W days warning threshhold\n"; + print STDERR "\t-C days critical threshold\n"; + print STDERR "\t-4 use IPv4 only\n"; + print STDERR "\t-U bytes EDNS0 UDP buffer size (default 4096)\n"; + exit 3; +} + +sub send_query { + my $qname = shift; + my $qtype = shift; + my $server = shift; + my $res = Net::DNS::Resolver->new; + $res->nameserver($server) if $server; + $res->udp_timeout($opts{t}); + $res->retry(2); + $res->recurse(0); + $res->dnssec(1); + $res->udppacketsize($opts{U}); + $res->force_v4(1) if $opts{'4'}; + my $pkt = $res->send($qname, $qtype); + unless ($pkt) { + $res->usevc(1); + $res->tcp_timeout($opts{t}); + $pkt = $res->send($qname, $qtype); + } + return $pkt; +} + +sub get_nslist { + my $pkt = shift; + return () unless $pkt; + return () unless $pkt->authority; + my @nslist; + foreach my $rr ($pkt->authority) { + next unless ($rr->type eq 'NS'); + next unless names_equal($rr->name, $zone); + push(@nslist, lc($rr->nsdname)); + } + return @nslist; +} + +sub names_equal { + my $a = shift; + my $b = shift; + $a =~ s/\.$//; + $b =~ s/\.$//; + lc($a) eq lc($b); +} + diff --git a/nagios/etc/23_postfix.cfg b/nagios/etc/23_postfix.cfg new file mode 100644 index 0000000..395fac4 --- /dev/null +++ b/nagios/etc/23_postfix.cfg @@ -0,0 +1,5 @@ +# Commande de check (essentiellement des perfs data) sur les logs de Postfix +command[check_postfix_log]=/usr/local/share/scripts-admin/nagios/check_postfix_log.sh + +# Commande de check sur les mails en attente +command[check_postfix_postqueue]=/usr/local/share/scripts-admin/nagios/check_postfix_postqueue.sh -w 2 -c 5 -W 21000000 -C 30000000 diff --git a/nagios/etc/24_sendmail.cfg b/nagios/etc/24_sendmail.cfg new file mode 100644 index 0000000..24ff393 --- /dev/null +++ b/nagios/etc/24_sendmail.cfg @@ -0,0 +1,22 @@ +# Commande de check (essentiellement des perfs data) sur les logs de Postfix +# TODO : à adapter (probablement refaire) +#command[check_postfix_log]=/usr/local/share/scripts-admin/nagios/check_postfix_log.sh + +# Commande de check sur les mails en attente +command[check_mail_queue]=/usr/local/share/scripts-admin/nagios/check_sendmail_queue.sh -w 1 -c 5 -W 21000000 -C 30000000 + +# mailstats de Sendmail +command[check_sendmail_mailstats]=/usr/local/share/scripts-admin/nagios/check_sendmail-mailstats.sh + +# Vérification des blacklists DNS (Spamhaus, etc.) +# Pour l'instant, on ne fait que spamhaus. À voir au fur et à mesure pour les autres. +# Exemple de liste : https://github.com/matteocorti/check_rbl +# 'domain' march'pas... +#command[check_rbl_domain]=perl /usr/local/share/scripts-admin/nagios/check_rbl -H example.net -t 15 -s cbl.anti-spam.org.cn -s cblplus.anti-spam.org.cn -s cblless.anti-spam.org.cn -s cdl.anti-spam.org.cn -s cbl.abuseat.org -s dnsbl.cyberlogic.net -s bl.deadbeef.com -s t1.dnsbl.net.au -s spamtrap.drbl.drand.net -s spamsources.fabel.dk -s 0spam.fusionzero.com -s mail-abuse.blacklist.jippg.org -s korea.services.net -s spamguard.leadmon.net -s ix.dnsbl.manitu.net -s relays.nether.net -s no-more-funn.moensted.dk -s psbl.surriel.com -s dyna.spamrats.com -s noptr.spamrats.com -s spam.spamrats.com -s dnsbl.sorbs.net -s dul.dnsbl.sorbs.net -s old.spam.dnsbl.sorbs.net -s problems.dnsbl.sorbs.net -s safe.dnsbl.sorbs.net -s spam.dnsbl.sorbs.net -s bl.spamcannibal.org -s bl.spamcop.net -s pbl.spamhaus.org -s sbl.spamhaus.org -s xbl.spamhaus.org -s ubl.unsubscore.com -s dnsbl-1.uceprotect.net -s dnsbl-2.uceprotect.net -s dnsbl-3.uceprotect.net -s db.wpbl.info +command[check_rbl_ipv4]=perl /usr/local/share/scripts-admin/nagios/check_rbl -H mail.example.net -t 15 -s cbl.anti-spam.org.cn -s cblplus.anti-spam.org.cn -s cblless.anti-spam.org.cn -s cdl.anti-spam.org.cn -s cbl.abuseat.org -s dnsbl.cyberlogic.net -s bl.deadbeef.com -s t1.dnsbl.net.au -s spamtrap.drbl.drand.net -s spamsources.fabel.dk -s 0spam.fusionzero.com -s mail-abuse.blacklist.jippg.org -s korea.services.net -s spamguard.leadmon.net -s ix.dnsbl.manitu.net -s relays.nether.net -s no-more-funn.moensted.dk -s psbl.surriel.com -s dyna.spamrats.com -s noptr.spamrats.com -s spam.spamrats.com -s dnsbl.sorbs.net -s dul.dnsbl.sorbs.net -s old.spam.dnsbl.sorbs.net -s problems.dnsbl.sorbs.net -s safe.dnsbl.sorbs.net -s spam.dnsbl.sorbs.net -s bl.spamcannibal.org -s bl.spamcop.net -s pbl.spamhaus.org -s sbl.spamhaus.org -s xbl.spamhaus.org -s ubl.unsubscore.com -s dnsbl-1.uceprotect.net -s dnsbl-2.uceprotect.net -s dnsbl-3.uceprotect.net -s db.wpbl.info +command[check_rbl_ipv6]=perl /usr/local/share/scripts-admin/nagios/check_rbl -H 2a01:abcd::abac:19 -t 15 -s cbl.anti-spam.org.cn -s cblplus.anti-spam.org.cn -s cblless.anti-spam.org.cn -s cdl.anti-spam.org.cn -s cbl.abuseat.org -s dnsbl.cyberlogic.net -s bl.deadbeef.com -s t1.dnsbl.net.au -s spamtrap.drbl.drand.net -s spamsources.fabel.dk -s 0spam.fusionzero.com -s mail-abuse.blacklist.jippg.org -s korea.services.net -s spamguard.leadmon.net -s ix.dnsbl.manitu.net -s relays.nether.net -s no-more-funn.moensted.dk -s psbl.surriel.com -s dyna.spamrats.com -s noptr.spamrats.com -s spam.spamrats.com -s dnsbl.sorbs.net -s dul.dnsbl.sorbs.net -s old.spam.dnsbl.sorbs.net -s problems.dnsbl.sorbs.net -s safe.dnsbl.sorbs.net -s spam.dnsbl.sorbs.net -s bl.spamcannibal.org -s bl.spamcop.net -s pbl.spamhaus.org -s sbl.spamhaus.org -s xbl.spamhaus.org -s ubl.unsubscore.com -s dnsbl-1.uceprotect.net -s dnsbl-2.uceprotect.net -s dnsbl-3.uceprotect.net -s db.wpbl.info + +# Le noyau va (a priori) choisir l'IP source des connexions de Sendmail +# dans l'ordre dans lequel elles sont configurées. On vérifie que l'IPv4 +# 192.168.2.25 est bien en tête. +command[check_first_ip]=/usr/local/share/scripts-admin/nagios/check_first_ip.sh -4 192.168.2.25 diff --git a/nagios/etc/30_nrpe-basic.cfg b/nagios/etc/30_nrpe-basic.cfg new file mode 100644 index 0000000..33c0ae9 --- /dev/null +++ b/nagios/etc/30_nrpe-basic.cfg @@ -0,0 +1,7 @@ +# Commandes de base pour serveur Linux +command[check_disks]=/usr/lib/nagios/plugins/check_disk -w 10% -c 5% -W 50% -K 5% -l -X tmpfs -X devpts -X usbfs +command[check_load]=/usr/lib/nagios/plugins/check_load -w 1,1,1 -c 3,2,2 +command[check_network_volume]=/usr/local/share/scripts-admin/nagios/check_network_volume.sh + +# Petite commande temporaire pour étudier souci neighbour table overflow +command[check_network-neighbour-table]=/usr/local/share/scripts-admin/nagios/check_network-neighbour-table.sh diff --git a/nagios/etc/33_nrpe-file-age.cfg b/nagios/etc/33_nrpe-file-age.cfg new file mode 100644 index 0000000..ec47f1e --- /dev/null +++ b/nagios/etc/33_nrpe-file-age.cfg @@ -0,0 +1,2 @@ +# Vérification de l'age de certains fichiers (en général, des sauvegardes) +command[check_file_age]=/usr/local/share/scripts-admin/nagios/check_file_age.sh -b /var/backups/pfsense -W 3:20 -f '*' diff --git a/nagios/etc/34_nrpe-config-replication.cfg b/nagios/etc/34_nrpe-config-replication.cfg new file mode 100644 index 0000000..17a2dac --- /dev/null +++ b/nagios/etc/34_nrpe-config-replication.cfg @@ -0,0 +1,9 @@ +# Vérification de la similitude des fichiers statiques sur les serveurs esclaves +# Pour utiliser, rajouter dans /etc/sudoers.d/nagios : +# nagios ALL=(ALL) NOPASSWD:/usr/local/sbin/check_differences_via_rsync.sh +command[check_config_replication]=sudo /usr/local/share/scripts-admin/nagios/check_differences_via_rsync.sh -s client-project-prod-srv2.example.net /etc/apache2/ /etc/libapache2-mod-jk/workers.properties /var/lib/tomcat7-multiinstances/*/webapps/ /root/patchs/ /etc/default/tomcat7_* + +# Verif sur réplication fichiers +# À l'inverse, cette commande doit être lancée côté serveurs esclaves +# pour vérifier que la réplication des uploads se fait bien. +command[check_file_age_replication]=/usr/lib/nagios/plugins/check_file_age -w 900 -c 36000 -f /srv/app/.nagios-check-file-age diff --git a/nagios/etc/40_check-updates.cfg b/nagios/etc/40_check-updates.cfg new file mode 100644 index 0000000..46a33a4 --- /dev/null +++ b/nagios/etc/40_check-updates.cfg @@ -0,0 +1,10 @@ +# Vérification de MAJ de la distribution +# +# Sous Debian, ajouter la ligne : +# APT::Periodic::Update-Package-Lists "1"; +# si possible dans un fichier nommé /etc/apt/apt.conf.d/02periodic +command[check_updates]=/usr/lib/nagios/plugins/check_apt + +# Sous CentOS, pour l'instant simple ajout de la ligne de /etc/crontab : +# 13 4,13,21 * * * root /usr/bin/yum -q -e 0 check-update +#command[check_updates]=/usr/lib64/nagios/plugins/check_updates -t 270 -w 3 -c 20 -a "--cacheonly" diff --git a/nagios/etc/41_temperature.cfg b/nagios/etc/41_temperature.cfg new file mode 100644 index 0000000..14b3799 --- /dev/null +++ b/nagios/etc/41_temperature.cfg @@ -0,0 +1,2 @@ +# Commande de check de la température des procs +command[check_temperature]=/usr/local/share/scripts-admin/nagios/check_temperature.sh -w 65 -c 80 diff --git a/nagios/etc/47_ide-smart.cfg b/nagios/etc/47_ide-smart.cfg new file mode 100644 index 0000000..12a3707 --- /dev/null +++ b/nagios/etc/47_ide-smart.cfg @@ -0,0 +1,7 @@ +# Commande pour vérifier l'état SMART des disques physiques +command[check_ide_smart_sda]=/usr/lib64/nagios/plugins/check_ide_smart -d /dev/sda +command[check_ide_smart_sdb]=/usr/lib64/nagios/plugins/check_ide_smart -d /dev/sdb +#command[check_ide_smart_sdc]=/usr/lib64/nagios/plugins/check_ide_smart -d /dev/sdc +#command[check_ide_smart_sdd]=/usr/lib64/nagios/plugins/check_ide_smart -d /dev/sdd +#command[check_ide_smart_sde]=/usr/lib64/nagios/plugins/check_ide_smart -d /dev/sde +#command[check_ide_smart_sdf]=/usr/lib64/nagios/plugins/check_ide_smart -d /dev/sdf diff --git a/nagios/etc/48_raid.cfg b/nagios/etc/48_raid.cfg new file mode 100644 index 0000000..922f9c8 --- /dev/null +++ b/nagios/etc/48_raid.cfg @@ -0,0 +1,2 @@ +# Check sur RAID Fusion MPT +command[check_raid]=/usr/lib/nagios/plugins/check_raid.pl diff --git a/nagios/etc/49_raid-linux.cfg b/nagios/etc/49_raid-linux.cfg new file mode 100644 index 0000000..b02e316 --- /dev/null +++ b/nagios/etc/49_raid-linux.cfg @@ -0,0 +1,2 @@ +# Commande pour vérifier l'état du RAID logiciel +command[check_raid_linux]=/usr/lib/nagios/plugins/check_raid_linux.pl diff --git a/nagios/etc/68_dell-openmanage.cfg b/nagios/etc/68_dell-openmanage.cfg new file mode 100644 index 0000000..416bd7d --- /dev/null +++ b/nagios/etc/68_dell-openmanage.cfg @@ -0,0 +1,3 @@ +# Commande basique pour check_openmanage +# Cf http://folk.uio.no/trondham/software/check_openmanage.html +command[check_openmanage]=/usr/lib/nagios/plugins/check_openmanage --perfdata diff --git a/nagios/etc/75_check-certificate.cfg b/nagios/etc/75_check-certificate.cfg new file mode 100644 index 0000000..c2d15a9 --- /dev/null +++ b/nagios/etc/75_check-certificate.cfg @@ -0,0 +1,6 @@ +# SMTP (SSL ou STARTTLS) +#command[check_certificate]=/usr/lib/nagios/plugins/check_smtp -H 127.0.0.1 --certificate=10,3 +# IMAPS (SSL) +#command[check_certificate]=/usr/lib/nagios/plugins/check_imap -H 127.0.0.1 -p 993 --certificate=30,5 -w 2 -c 30 +# TCP de base (HTTPS par exemple +command[check_certificate]=/usr/lib/nagios/plugins/check_tcp -H 127.0.0.1 -p 443 --certificate=10,5 -w 2 -c 30 diff --git a/nagios/etc/76_netstat.cfg b/nagios/etc/76_netstat.cfg new file mode 100644 index 0000000..2eadb7d --- /dev/null +++ b/nagios/etc/76_netstat.cfg @@ -0,0 +1,3 @@ +# Commande de check sur le nombre de connexions TCP et UDP +command[check_netstat_connectioncount]=/usr/local/share/scripts-admin/nagios/check_netstat_connectioncount.sh -w 1:3 -c 1:5 -p 22 +#command[check_netstat_connectioncount]=/usr/local/share/scripts-admin/nagios/check_netstat_connectioncount.sh -w 1:3 -c 1:5 -p 22 -w 1:100 -c 1:200 -p80 -p 443 diff --git a/nagios/etc/78_ntpserver.cfg b/nagios/etc/78_ntpserver.cfg new file mode 100644 index 0000000..9233866 --- /dev/null +++ b/nagios/etc/78_ntpserver.cfg @@ -0,0 +1,2 @@ +# Vérification sur le serveur local NTP +command[check_ntp_peer]=/usr/lib/nagios/plugins/check_ntp_peer -H 127.0.0.1 -w 2 -c 60 --jwarn=2 --jcrit=5 --twarn=3:10 --tcrit=2:20 --swarn=4 --scrit=6 diff --git a/nagios/etc/80_check-apache.cfg b/nagios/etc/80_check-apache.cfg new file mode 100644 index 0000000..0c5819e --- /dev/null +++ b/nagios/etc/80_check-apache.cfg @@ -0,0 +1,3 @@ +# check_apache_serverstatus.pl récupéré depuis https://github.com/SteScho/apache_serverstatus +command[check_apache]=/usr/local/share/scripts-admin/nagios/check_apache_serverstatus.pl -H localhost --warncrit=.,3:,1: --wc=BytesPerSec,100000,200000 +command[check_apache_access_log]=/usr/local/share/scripts-admin/nagios/check_apache_access_log.pl -f /var/log/apache2/access.log diff --git a/nagios/etc/83_check-wordpress.cfg b/nagios/etc/83_check-wordpress.cfg new file mode 100644 index 0000000..fe8c7a5 --- /dev/null +++ b/nagios/etc/83_check-wordpress.cfg @@ -0,0 +1 @@ +command[check_wordpress]=php /usr/local/share/scripts-admin/nagios/check_wp.php --dir /var/www/wordpress diff --git a/nagios/etc/README.txt b/nagios/etc/README.txt new file mode 100644 index 0000000..058a511 --- /dev/null +++ b/nagios/etc/README.txt @@ -0,0 +1,25 @@ +Petits exemples de fichiers récupérés dans les /etc/nagios/nrpe.d/ à droite à gauche. + +Je les regroupe ici juste pour éviter d'avoir à les rechercher sur chacun des serveurs : ce ne sont pas des sauvegardes, ni des modèles immuables. Bien penser à adapter ces appels NRPE à chaque serveur (et lire la doc des plugins utilisés :) + + +Pour info, le nrpe_local : +###################################### +# Do any local nrpe configuration here +###################################### +allowed_hosts=2a01:cb04:a52:f900::abac:22 +ssl_version=TLSv1.2+ +ssl_cipher_list=HIGH +ssl_cacert_file=/etc/ssl/nagios/bugness-monitoring-ca.pem +ssl_cert_file=/etc/ssl/nagios/TODO.bugness.org.crt +ssl_privatekey_file=/etc/ssl/nagios/TODO.bugness.org.key + +# SSL USE CLIENT CERTS +# This options determines client certificate usage. +# Values: 0 = Don't ask for or require client certificates (default) +# 1 = Ask for client certificates +# 2 = Require client certificates +ssl_client_certs=2 + +# Note Bugness: quoi qu'on fasse, ça semble être désactivé. Mais on le spécifie quand même +ssl_use_adh=0 diff --git a/nagios/patch_nagios-plugins-check_disk.diff b/nagios/patch_nagios-plugins-check_disk.diff new file mode 100644 index 0000000..da6227a --- /dev/null +++ b/nagios/patch_nagios-plugins-check_disk.diff @@ -0,0 +1,10 @@ +--- nagios-plugins-1.4.15/plugins/check_disk.c 2010-07-27 22:47:16.000000000 +0200 ++++ check_disk.c 2012-06-05 21:17:26.650825165 +0200 +@@ -314,6 +314,7 @@ + me->me_mountdir, total, available, available_to_root, used, fsp.fsu_files, fsp.fsu_ffree); + + dused_pct = calculate_percent( used, used + available ); /* used + available can never be > uintmax */ ++ total = used + available; + + dfree_pct = 100 - dused_pct; + dused_units = used*fsp.fsu_blocksize/mult; diff --git a/nagios/utils.sh b/nagios/utils.sh new file mode 100644 index 0000000..a7706e7 --- /dev/null +++ b/nagios/utils.sh @@ -0,0 +1,123 @@ +#! /bin/sh + +# Note chl-dev@bugness.org +# Fichier pris sur la dernière version de nagios-plugins au 2012-12-10 +# https://github.com/nagios-plugins/nagios-plugins +# car la version dispo sur Debian n'a pas encore la fonction check_range() +# À supprimer dès qu'envisageable. + +STATE_OK=0 +STATE_WARNING=1 +STATE_CRITICAL=2 +STATE_UNKNOWN=3 +STATE_DEPENDENT=4 + +if test -x /usr/bin/printf; then + ECHO=/usr/bin/printf +else + ECHO=echo +fi + +print_revision() { + echo "$1 v$2 (nagios-plugins 1.4.16)" + $ECHO "The nagios plugins come with ABSOLUTELY NO WARRANTY. You may redistribute\ncopies of the plugins under the terms of the GNU General Public License.\nFor more information about these matters, see the file named COPYING.\n" | sed -e 's/\n/ /g' +} + +support() { + $ECHO "Send email to nagios-users@lists.sourceforge.net if you have questions\nregarding use of this software. To submit patches or suggest improvements,\nsend email to nagiosplug-devel@lists.sourceforge.net.\nPlease include version information with all correspondence (when possible,\nuse output from the --version option of the plugin itself).\n" | sed -e 's/\n/ /g' +} + +# +# check_range takes a value and a range string, returning successfully if an +# alert should be raised based on the range. Range values are inclusive. +# Values may be integers or floats. +# +# Example usage: +# +# Generating an exit code of 1: +# check_range 5 2:8 +# +# Generating an exit code of 0: +# check_range 1 2:8 +# +check_range() { + local v range yes no err decimal start end cmp match + v="$1" + range="$2" + + # whether to raise an alert or not + yes=0 + no=1 + err=2 + + # regex to match a decimal number + decimal="-?([0-9]+\.?[0-9]*|[0-9]*\.[0-9]+)" + + # compare numbers (including decimals), returning true/false + cmp() { awk "BEGIN{ if ($1) exit(0); exit(1)}"; } + + # returns successfully if the string in the first argument matches the + # regex in the second + match() { echo "$1" | grep -E -q -- "$2"; } + + # make sure value is valid + if ! match "$v" "^$decimal$"; then + echo "${0##*/}: check_range: invalid value" >&2 + unset -f cmp match + return "$err" + fi + + # make sure range is valid + if ! match "$range" "^@?(~|$decimal)(:($decimal)?)?$"; then + echo "${0##*/}: check_range: invalid range" >&2 + unset -f cmp match + return "$err" + fi + + # check for leading @ char, which negates the range + if match $range '^@'; then + range=${range#@} + yes=1 + no=0 + fi + + # parse the range string + if ! match "$range" ':'; then + start=0 + end="$range" + else + start="${range%%:*}" + end="${range#*:}" + fi + + # do the comparison, taking positive ("") and negative infinity ("~") + # into account + if [ "$start" != "~" ] && [ "$end" != "" ]; then + if cmp "$start <= $v" && cmp "$v <= $end"; then + unset -f cmp match + return "$no" + else + unset -f cmp match + return "$yes" + fi + elif [ "$start" != "~" ] && [ "$end" = "" ]; then + if cmp "$start <= $v"; then + unset -f cmp match + return "$no" + else + unset -f cmp match + return "$yes" + fi + elif [ "$start" = "~" ] && [ "$end" != "" ]; then + if cmp "$v <= $end"; then + unset -f cmp match + return "$no" + else + unset -f cmp match + return "$yes" + fi + else + unset -f cmp match + return "$no" + fi +} diff --git a/oldies/lib_gestion-mailinglists.sh b/oldies/lib_gestion-mailinglists.sh new file mode 100644 index 0000000..d7d84cd --- /dev/null +++ b/oldies/lib_gestion-mailinglists.sh @@ -0,0 +1,123 @@ +# Ici se trouvent réunies les fonctions et la configuration utiles au script +# de gestion des mailing-lists + +# Config +LDAP_HOST="ldap.example.net" +LDAP_ROOT="dc=example,dc=net" +CONFIG_IDENTIFIANTS_SMBLDAP="/etc/smbldap-tools/smbldap_bind.conf" + +. $CONFIG_IDENTIFIANTS_SMBLDAP +LDAP_PASSWD="$masterPw" +LDAP_BIND_DN="$masterDN" + + +# Liste, sur stdout, les mailing-lists dont fait déjà parti l'adresse +# email fournie en argument. +# args: email +# +# note : effectué en connexion anonyme. A priori, les droits sont suffisants. +afficher_abonnements_en_cours() { + ldapsearch -x -h "$LDAP_HOST" -b "ou=mailing-lists,$LDAP_ROOT" -LLL "(rfc822MailMember=$1)" cn | sed -n 's/^cn: \(.*\)/\1/p' | sort +} + +# Affiche la liste des mailing-lists +# +# note : effectué en connexion anonyme. A priori, les droits sont suffisants. +afficher_listing_mailinglists() { + ldapsearch -x -h "$LDAP_HOST" -b "ou=mailing-lists,$LDAP_ROOT" -LLL cn | sed -n 's/^cn: \(.*\)/\1/p' | sort +} + +# Affiche la liste des abonnés d'une mailing-list +# args: mailing-list +# +# note : effectué en connexion anonyme. A priori, les droits sont suffisants. +afficher_abonnes_mailinglist() { + ldapsearch -x -h "$LDAP_HOST" -b "cn=$1,ou=mailing-lists,$LDAP_ROOT" -LLL rfc822MailMember | sed -n 's/^rfc822MailMember: //p' +} + +# Supprime l'email d'une mailing-list +# args: email, mailing-list +supprimer_abonnement() { + # Ecriture du mot de passe + LDAP_PASSWDFILE=$( mktemp ) + printf "%s" "$LDAP_PASSWD" >$LDAP_PASSWDFILE + + # Requete + cat <$LDAP_PASSWDFILE + + # Requête + cat <$LDAP_PASSWDFILE + + # Requete + cat <$LDAP_PASSWDFILE + + # Requete + cat <&2 + exit 1 + ;; + esac +done +shift $( expr $OPTIND - 1 ) +HOSTNAME_PFSENSE="$1" +BASE_NAME=$( printf "%s" $( basename "$REPDRUPAL" ) | tr -c "a-zA-Z" "-" ) + +if [ -z "$HOSTNAME_PFSENSE" ]; then + echo "ERREUR: veuillez indiquer un hostname (ou une IP)." >&2 + clean_up_and_exit 1 +fi +if [ ! -d "$BASE_DIR" ]; then + echo "ERREUR: repertoire de destination '$BASE_DIR' inexistant." >&2 + clean_up_and_exit 1 +fi + +# Récupération du CSRF +CSRF_MAGIC="$( wget -q -O - --keep-session-cookies --save-cookies "$COOKIES_FILE" https://$HOSTNAME_PFSENSE/index.php | sed -n "s/.*&2 + clean_up_and_exit 1 +fi + +# Authentification +if ! wget -q -O /dev/null --keep-session-cookies --save-cookies "$COOKIES_FILE" --load-cookies "$COOKIES_FILE" --post-data "__csrf_magic=$CSRF_MAGIC&usernamefld=$USERNAME&passwordfld=$PASSWORD&login=Login" https://$HOSTNAME_PFSENSE/index.php; then + echo "ERREUR: echec a la premiere connexion." >&2 + clean_up_and_exit 1 +fi + +# On vérifie que l'on est bien connecté +if [ $( wget -q -O - --keep-session-cookies --save-cookies "$COOKIES_FILE" --load-cookies "$COOKIES_FILE" https://$HOSTNAME_PFSENSE/diag_backup.php | grep -c "Diagnostics: Backup/restore" ) -lt 1 ]; then + echo "ERREUR: impossible d'accéder à la page de backup." >&2 + clean_up_and_exit 1 +fi + +#Config. seule +wget -q -O "$BASE_DIR/$PREFIXE$BASE_NAME$HOSTNAME_PFSENSE-conf_$SUFFIXE.xml" --keep-session-cookies --save-cookies "$COOKIES_FILE" --load-cookies "$COOKIES_FILE" --post-data "Submit=Download%20configuration&donotbackuprrd=on" https://$HOSTNAME_PFSENSE/diag_backup.php +#Config + données RRD +wget -q -O "$BASE_DIR/$PREFIXE$BASE_NAME$HOSTNAME_PFSENSE-confrrd_$SUFFIXE.xml" --keep-session-cookies --save-cookies "$COOKIES_FILE" --load-cookies "$COOKIES_FILE" --post-data "Submit=Download%20configuration" https://$HOSTNAME_PFSENSE/diag_backup.php + +# Suppression des vieux backups +if [ "$DUREE_DE_VIE" -ne "0" ]; then + find $BASE_DIR -name "$PREFIXE$BASE_NAME$HOSTNAME_PFSENSE-conf_*.xml" -mtime "+$DUREE_DE_VIE" -print0 | xargs -n 200 -r -0 rm -f + find $BASE_DIR -name "$PREFIXE$BASE_NAME$HOSTNAME_PFSENSE-confrrd_*.xml" -mtime "+$DUREE_DE_VIE" -print0 | xargs -n 200 -r -0 rm -f +fi + +clean_up_and_exit 0 diff --git a/oldies/sauvegarde_samba.sh b/oldies/sauvegarde_samba.sh new file mode 100755 index 0000000..a0cea53 --- /dev/null +++ b/oldies/sauvegarde_samba.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +# Configuration +# Le fichier sera nommé BASE_DIR/PREFIXEbasenameSUFFIXE +BASE_DIR=/var/backups/bdd-samba +PREFIXE=sauv_samba_ +SUFFIXE=_$( date +%Y%m%d-%H%M ).tar.gz +DUREE_DE_VIE=100 + +# Vérifications initiales +if [ ! -d "$BASE_DIR" ]; then + echo "ERREUR : répertoire de sauvegarde inexistant : $BASE_DIR ." >&2 + exit 1 +fi + +# Sauvegarde +cd /var/lib +tar -czf "$BASE_DIR/$PREFIXE"example.net"$SUFFIXE" samba + +# Suppression des anciennes sauvegardes +if [ "$1" = "--delete-olds" ]; then + find $BASE_DIR -name "$PREFIXE*" -mtime +$DUREE_DE_VIE -print0 | xargs -n 200 -r -0 rm -f +fi + + diff --git a/oldies/script_ajout-utilisateur.sh b/oldies/script_ajout-utilisateur.sh new file mode 100755 index 0000000..b472420 --- /dev/null +++ b/oldies/script_ajout-utilisateur.sh @@ -0,0 +1,242 @@ +#!/bin/sh + +# Ce script aide à la création d'un compte LDAP +# Il s'occupe : +# - création LDAP/SMB +# - mot de passe +# - création de la boîte Cyrus +# - ajout aux listes d'emails (salaries@example.net, ...) + +# Ce script nécessite : +# - des identifiants admin sur les listes emails (utilisation des identifiants smbldap pour l'instant. Pas glop.) +# - des identifiants admin sur Cyrus. Ces identifiants seront contenus dans le fichier $CONFIG_IDENTIFIANTS_CYRUS, au format : +# user=LOGIN +# password=PASS + + +# Config +LDAP_HOST="ldap.example.net" +LDAP_ROOT="dc=example,dc=net" +CYRUS_HOST="messagerie.example.net" +CONFIG_EMAIL_DOMAIN="example.net" +CONFIG_DEFAULT_GID=513 +CONFIG_DEFAULT_QUOTA=1048576 +CONFIG_IDENTIFIANTS_SMBLDAP="/etc/smbldap-tools/smbldap_bind.conf" +CONFIG_IDENTIFIANTS_CYRUS="/root/.cyrus_auth" + +# Petite mise en bouche +cat <&2 + + return 1 + fi + + #TODO : vérif syntaxe + test "$1" != "" +} + +check_login() { + # n'accepte que les minuscules et les chiffres (doit commencer par une lettre) + + # locale "C" pour que [a-z] ne contienne pas à, é, ... + OLDLANG="$LANG" + LANG="C" + RETURN=0 + # Passage à la regexp de la mort + if [ $( printf "%s" "$1" | egrep -c "^[a-z][a-z0-9]{2,7}$" ) -ne 1 ]; then + RETURN=1 + # Si le login est vide, on reste clément et rien n'est affiché + test -n "$1" && echo "ERREUR: login non valide (regexp: ^[a-z][a-z0-9]{2,7}$ )" >&2 + fi + LANG="$OLDLANG" + test "$RETURN" -eq 0 || return 1 + + # Vérification que le login (=uid LDAP) n'est pas déjà utilisé + if [ $( ldapsearch -x -h "$LDAP_HOST" -b "ou=users,$LDAP_ROOT" -LLL "uid=$1" | grep -c "^dn: " ) -gt 0 ]; then + echo "ERREUR: login déjà existant." >&2 + return 1 + fi +} + +check_unix_homedir() { + # Rien à faire (?) + test "$1" != "" # renvoie false si $1 vide +} + +generate_default_email() { + # Initiale du prénom + nom + RETURN=$( printf "%.01s%s@%s" "$1" "$2" "$CONFIG_EMAIL_DOMAIN" | tr "A-Z" "a-z" ) + + # Suppression des caractères spéciaux et sortie de la fonction + LANG=C echo "$RETURN" | tr -dc "a-z0-9-.@" +} + +generate_default_login() { + # on se base lâchement sur generate_default_email :) + # (TODO : bugs divers si prénom + nom < 3 caractères...) + printf "%.03s" $( generate_default_email "$1" "$2" ) +} + +generate_default_unix_homedir() { + # On renvoie simplement /home/LOGIN + echo "/home/$1" +} + + + +# Enfin : le code... +# 1ère étape : on demande interactivement toutes les infos +# et on crée le compte + mot de passe + +#Prénom +while ! check_string "$PRENOM"; do + printf "Prénom : "; read PRENOM +done + +#Nom +while ! check_string "$NOM"; do + printf "Nom : "; read NOM +done + +#login +DEFAULT_LOGIN=$( generate_default_login "$PRENOM" "$NOM" ) +while ! check_login "$LOGIN"; do + printf "Login [%s] : " "$DEFAULT_LOGIN"; read LOGIN + test "$LOGIN" = "" && LOGIN="$DEFAULT_LOGIN" +done + +#email +DEFAULT_EMAIL=$( generate_default_email "$PRENOM" "$NOM" ) +while ! check_email "$EMAIL"; do + # Prompt avec proposition + printf "Email [%s] : " "$DEFAULT_EMAIL"; read EMAIL + # Si l'utilisateur laisse le champ vide : utilisation de la proposition + test "$EMAIL" = "" && EMAIL="$DEFAULT_EMAIL" +done + +#Home directory (UNIX) +DEFAULT_UNIX_HOMEDIR=$( generate_default_unix_homedir "$LOGIN" ) +while ! check_unix_homedir "$UNIX_HOMEDIR"; do + printf "Homedir [%s] : " "$DEFAULT_UNIX_HOMEDIR"; read UNIX_HOMEDIR + test "$UNIX_HOMEDIR" = "" && UNIX_HOMEDIR="$DEFAULT_UNIX_HOMEDIR" +done + + +# Création du compte avec smbldap-useradd + demande du mot de passe +echo "Création du compte dans LDAP... (éviter le Ctrl-C à partir de maintenant)" +if ! smbldap-useradd -a -g $CONFIG_DEFAULT_GID -M "$EMAIL" -N "$PRENOM" -S "$NOM" -d "$UNIX_HOMEDIR" "$LOGIN"; then + echo "ERREUR: smbldap-useradd a renvoyé une erreur. Arrêt du script $0." >&2 + return 1 +fi +echo "Compte LDAP créé." +echo + +# mot de passe +echo "Veuillez renseigner le mot de passe..." +TMP="" +while test "$TMP" = "" && ! smbldap-passwd "$LOGIN"; do + echo "WARNING: problème sur le mot de passe." >&2 + printf "Voulez-vous réessayer ? (O/n)" + read TMP + if [ $( echo "$TMP" | egrep -ic "^o$" ) -eq 1 ]; then + TMP="" + fi +done +echo + + +# 2ème étape : création de la boîte mail dans Cyrus +# +# Tout se fait via un script Perl parce que les outils d'admin +# de Cyrus sont pas franchement faciles à scripter... +printf "Créer la boîte mail dans Cyrus ? (O/n)" +read TMP +if [ -n "$TMP" ] && [ $( echo "$TMP" | egrep -ic "^o$" ) -eq 0 ]; then + echo "Ah bon ?! Ben à la prochaine alors." >&2 + return 0 +fi + +RACINE_EMAIL=$( echo "$EMAIL" | sed 's/@.*//' ) +cat <new('$CYRUS_HOST') or die "Echec de connexion."; + + # Lecture du fichier de configuration + open CONFIG, '$CONFIG_IDENTIFIANTS_CYRUS'; + while () { + chomp; # no newline + s/^#.*//; # no comments + s/^\s+//; # no leading white + s/\s+$//; # no trailing white + next unless length; # anything left? + my (\$var, \$value) = split(/\s*=\s*/, \$_, 2); + \$cyrus_config{\$var} = \$value; + } + + # Authentification + \$conn->authenticate( + "-user" => \$cyrus_config{'user'}, + "-password" => \$cyrus_config{'password'}, + "-mechanism" => 'LOGIN', + ) or die "Echec à l'authentification."; + + # Création de la boîte Cyrus + \$conn->create('user.$RACINE_EMAIL') or die "Echec à la création de la boîte ('va falloir aller voir à la main si qqchose a été fait...)"; + + # Spécification du quota + \$conn->setquota('user.$RACINE_EMAIL', 'STORAGE', '$CONFIG_DEFAULT_QUOTA') or die "Echec lors de la mise en place du quota"; +EOF + +if [ "$?" -eq 0 ]; then + echo "Boîte créée." +else + echo "ERREUR: erreur à la création de la boîte. Le compte LDAP existe néamoins. Voir avec Cyrus. Abandon." >&2 + return 1 +fi +echo + + +# 3ème étape : les listes mails +echo "Ajout aux mailing-lists..." +if ! ./script_ml-gestion-abonne.sh -a salaries -i "$EMAIL"; then + cat <&2 +NOTICE: apparemment, il y a eu un pépin à la gestion des mailing-lists. + Le compte est néanmoins créé, on vous laisse vous débrouiller avec + ./script_ml-gestion-abonne.sh ou PHPLDAPAdmin. + + Cordialement. +EOF +return 1 +fi + +# 4ème étape : envoi du mail de bienvenue +# TODO + + +echo "Fin du script." diff --git a/oldies/script_deploiement-massif-war.sh b/oldies/script_deploiement-massif-war.sh new file mode 100755 index 0000000..7915b87 --- /dev/null +++ b/oldies/script_deploiement-massif-war.sh @@ -0,0 +1,136 @@ +#!/bin/sh + +RACINE_MULTIINSTANCES="/var/lib/tomcat7-multiinstances" +RACINE_PATCHS="$HOME/patchs" +WAR_FILE="" +WEBAPP_NAME="ROOT" +RELANCE_AUTO_TOMCAT=1 +JUST_TEST_THE_PATCHS=0 + +set -e + +# Fonctions +# fonction d'aide +usage() { +cat <&2 + exit 1 + ;; + esac +done +shift $( expr $OPTIND - 1 ) +#REPDRUPAL="$1" + +# Petites vérifs +if [ ! -f "$WAR_FILE" ]; then + echo "ERREUR: fichier '$WAR_FILE' introuvable." >&2 + exit 1 +fi + +# Vérification des patchs +echo "INFO: vérification des patchs..." +# on dézippe le war dans un dossier temporaire +TEMP_REP=$( mktemp -d ) +cd "$TEMP_REP" +unzip -q "$WAR_FILE" +# ... et on boucle sur chacun de patchs demandés +for INSTANCE in $@; do + echo "$INSTANCE" + if [ ! -f $RACINE_PATCHS/$INSTANCE.diff ]; then + echo "ERREUR: patch inexistant pour l'instance '$INSTANCE'." >&2 + exit 1 + fi + if ! patch --dry-run -p1 < $RACINE_PATCHS/$INSTANCE.diff; then + echo "ERREUR: patch non applicable sur instance $INSTANCE." >&2 + exit 1 + fi +done +cd / +rm -rf "$TEMP_REP" +# Si on se contentait de tester les patchs, on s'arrête là +[ "$JUST_TEST_THE_PATCHS" -eq 1 ] && exit 0 + +# Déploiement +echo "INFO: déploiement..." +for INSTANCE in $@; do + echo "$INSTANCE" + # Dézippage du war dans un dossier temporaire + cd "$RACINE_MULTIINSTANCES/$INSTANCE" + mkdir ROOT_new + cd ROOT_new + unzip -q "$WAR_FILE" + # Patch de la copie dézippée + patch -p1 < $RACINE_PATCHS/$INSTANCE.diff + + # Relance de tomcat + if [ "$RELANCE_AUTO_TOMCAT" -ne 0 ]; then + service $INSTANCE stop + sleep 3 + rm -rf "../webapps/$WEBAPP_NAME" + mv -i ../ROOT_new "../webapps/$WEBAPP_NAME" + service $INSTANCE start + else + # TODO : affichage des commandes ? + true + fi +done diff --git a/oldies/script_inotify-rsync.sh b/oldies/script_inotify-rsync.sh new file mode 100755 index 0000000..b3647eb --- /dev/null +++ b/oldies/script_inotify-rsync.sh @@ -0,0 +1,128 @@ +#!/bin/sh + +# Configuration +DIR_SOURCE="" +DIR_DESTINATION="" +MAX_WAIT=60 +RSYNC_OPTIONS="-q -aH --delete" +INOTIFYWAIT_OPTIONS="-qq -r -e close_write -e attrib -e move -e create -e delete -e unmount" +#RSYNC_OPTIONS="-v -aH --delete" +#INOTIFYWAIT_OPTIONS="-r -e close_write -e attrib -e move -e create -e delete -e unmount" + +# On essaie de diminuer la priorité de la chose +# Aucune importance si les utilitaires ne sont pas dispos +renice 15 -p $$ >/dev/null 2>&1 +ionice -c 3 -p $$ >/dev/null 2>&1 + +# Arrêt à la moindre erreur non-catchée +set -e + +# Fonctions +# Little helper to centralize syslog calls +loglog() { + LEVEL="$1" + shift + logger -s -t inotify-rsync -p user.$LEVEL $@ +} + +# affiche le message d'aide +usage() { +cat <&2 + exit 1 + ;; + esac +done +#shift $( expr $OPTIND - 1 ) +#REPDRUPAL="$1" + +# Some checks +if [ -z "$DIR_SOURCE" ] || [ ! -d "$DIR_SOURCE" ]; then + loglog err "ERROR: no source specified or directory inexistent." >&2 + exit 1 +fi +if [ -z "$DIR_DESTINATION" ]; then + loglog err "ERROR: no destination specified." >&2 + exit 1 +fi + +while true; do + # rsync can send error code != 0, we'll have to check + # what this code means before failing + set +e + rsync $RSYNC_OPTIONS "$DIR_SOURCE" "$DIR_DESTINATION" + RSYNC_RETURN_CODE="$?" + set -e + while [ "$RSYNC_RETURN_CODE" -ne "0" ]; do + for i in 24; do + if [ "$RSYNC_RETURN_CODE" -eq "$i" ]; then + # If the return code is "acceptable", we go on + loglog debug "DEBUG: rsync returned code '$RSYNC_RETURN_CODE'" + break 2 + fi + done + # The return code wasn't in the "acceptable" list => log + exit + loglog err "ERROR: rsync returned unexpected error code : $RSYNC_RETURN_CODE. Script stopped." + exit $RSYNC_RETURN_CODE + done + + # Wait for another change + # inotifywait can send error code != 0, we'll have to check + # what this code means before failing + set +e + inotifywait $INOTIFYWAIT_OPTIONS -t "$MAX_WAIT" "$DIR_SOURCE" + INOTIFYWAIT_RETURN_CODE="$?" + set -e + if [ "$INOTIFYWAIT_RETURN_CODE" -ne "0" ]; then + if [ "$INOTIFYWAIT_RETURN_CODE" -ne "2" ]; then + loglog err "ERROR: inotifywait returned unexpected error code : $INOTIFYWAIT_RETURN_CODE. Script stopped." + exit $INOTIFYWAIT_RETURN_CODE + fi + fi +done diff --git a/oldies/script_inotify-rsync_startup-script.sh b/oldies/script_inotify-rsync_startup-script.sh new file mode 100755 index 0000000..a818462 --- /dev/null +++ b/oldies/script_inotify-rsync_startup-script.sh @@ -0,0 +1,138 @@ +#! /bin/sh +### BEGIN INIT INFO +# Provides: rsync-inotify +# Required-Start: $syslog $local_fs $network +# Required-Stop: $syslog $local_fs $network +# Should-Start: $named +# Should-Stop: $named +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Rsync-inotify launcher +# Description: This script launch the rsync-inotify script on the upload +# of the XXX instances project. +### END INIT INFO + +# Do NOT "set -e" + +# PATH should only include /usr/* if it runs after the mountnfs.sh script +PATH=/sbin:/usr/sbin:/bin:/usr/bin +DESC="Rsync-Inotify for XXX instances" +NAME=inotify-rsync +DAEMON=/root/script_inotify-rsync.sh +# J'arrive pas à le faire passer correctement à start-stop-daemon :-( +#DAEMON_ARGS='-r "-q -aH --delete --password-file=/root/.inotify-rsync-password" -s /srv/XXX/ -d "rsync://XXX-storage-master@srv2.example.net/XXX-storage/"' +PIDFILE=/var/run/$NAME.pid +SCRIPTNAME=/etc/init.d/inotify-rsync.sh + + + +# Exit if the package is not installed +[ -x "$DAEMON" ] || exit 0 + +# Read configuration variable file if it is present +[ -r /etc/default/$NAME ] && . /etc/default/$NAME + +# Load the VERBOSE setting and other rcS variables +. /lib/init/vars.sh + +# Define LSB log_* functions. +# Depend on lsb-base (>= 3.2-14) to ensure that this file is present +# and status_of_proc is working. +. /lib/lsb/init-functions + +# +# Function that starts the daemon/service +# +do_start() +{ + # Return + # 0 if daemon has been started + # 1 if daemon was already running + # 2 if daemon could not be started + if [ -n "$( pgrep -f "$DAEMON" )" ]; then + return 1 + fi + + start-stop-daemon --start -b --make-pidfile --iosched idle --nicelevel 10 --exec "$DAEMON" --pidfile "$PIDFILE" --test > /dev/null \ + || return 1 + start-stop-daemon --start -b --make-pidfile --iosched idle --nicelevel 10 --exec "$DAEMON" --pidfile "$PIDFILE" -- \ + -r "-q -aH --delete --password-file=/root/.inotify-rsync-password" -s /srv/XXX/ -d "rsync://storage-master@srv2.example.net/XXX-storage/" \ + || return 2 +} + +# +# Function that stops the daemon/service +# +do_stop() +{ + # Return + # 0 if daemon has been stopped + # 1 if daemon was already stopped + # 2 if daemon could not be stopped + # other if a failure occurred + + # Petite vérification supplémentaire : + # comme on ne semble pas pouvoir utiliser l'option --exec avec le --stop + # de start-stop-daemon, on vérifie que le PID dans PID_FILE correspond bien + # notre process + PID_CHECK="$( pgrep -f "$DAEMON" )" + if [ -z "$PID_CHECK" ] || [ "$PID_CHECK" != "$( cat "$PIDFILE" 2>/dev/null )" ]; then + return 2 + fi + + # start-stop-daemon ne semble pas arrêter proprement le inotifywait qui reste + # zombifié jusqu'à son timeout. Du coup, on commence par pkill + pkill --signal INT -P "$PID_CHECK" || return 2 + if [ -n "$( pgrep -f "$DAEMON" )" ]; then + start-stop-daemon --stop --quiet --retry=INT/5/KILL/5 --pidfile "$PIDFILE" + fi + + RETVAL="$?" + [ "$RETVAL" = 2 ] && return 2 + # Many daemons don't delete their pidfiles when they exit. + rm -f $PIDFILE + return "$RETVAL" +} + +case "$1" in + start) + [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" + do_start + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + stop) + [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" + do_stop + case "$?" in + 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; + 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; + esac + ;; + restart|force-reload) + log_daemon_msg "Restarting $DESC" "$NAME" + do_stop + case "$?" in + 0|1) + do_start + case "$?" in + 0) log_end_msg 0 ;; + 1) log_end_msg 1 ;; # Old process is still running + *) log_end_msg 1 ;; # Failed to start + esac + ;; + *) + # Failed to stop + log_end_msg 1 + ;; + esac + ;; + *) + echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2 + exit 3 + ;; +esac + +: diff --git a/oldies/script_listing-volumetrie-backuppc.sh b/oldies/script_listing-volumetrie-backuppc.sh new file mode 100755 index 0000000..f6d82f6 --- /dev/null +++ b/oldies/script_listing-volumetrie-backuppc.sh @@ -0,0 +1,54 @@ +#!/bin/sh + +BASE_REP="/backuppc/backuppc/pc" + +MAX_NBLIGNES_INCR=30 +LISTING_FULL=$(printf "%s\n\t%s\t%s\n" "Volumes des dernières sauvegardes complètes :" "Nb fichiers" "Taille" ) +LISTING_INCR=$(printf "%s\n\t%s\t%s\n" "Volumes des $MAX_NBLIGNES_INCR dernières sauvegardes incrémentales :" "Nb fichiers" "Taille" ) + +somme_ligne() { + TOTAL_FILES=0 + TOTAL_SIZE=0 + + # note : c'est un peu sale. + # Explications : on fait une boucle basée sur un pipe, les variables dans cette boucle + # deviennent donc locales à cette boucle. + # 'faut que je retrouve comment en sortir proprement + cat - | while read line; do + echo $(( $TOTAL_FILES + $(printf "%s" "$line" | awk 'BEGIN { FS = "\t" } ; { print $5 }' ) )) + TOTAL_FILES=$(( $TOTAL_FILES + $( printf "%s" "$line" | awk 'BEGIN { FS = "\t" } ; { print $5 }' ) )) + TOTAL_SIZE=$(( $TOTAL_SIZE + $( printf "%s" "$line" | awk 'BEGIN { FS = "\t" } ; { print $6 }' ) )) + printf "%d\t%d\n" "$TOTAL_FILES" "$TOTAL_SIZE" + done | tail -n 1 +} + +cd "$BASE_REP" + +for REP in *; do + # On ne prend que les dossiers qui contiennent un fichier non-vide "backups" + if [ ! -d "$REP" ]; then + continue + fi + if [ ! -s "$REP/backups" ]; then + continue + fi + + # Listing full + LISTING_FULL="$( printf "%s\n%s\t%s" "$LISTING_FULL" "$REP" "$( cat "$REP/backups" | egrep "^[0-9]+[[:space:]]+full" | tail -n 1 | somme_ligne )" )" + + # Listing incrémental + #décompte nb sauv. + NBLIGNES_INCR="$( cat "$REP/backups" | egrep "^[0-9]+[[:space:]]+incr" | wc -l )" + if [ "$NBLIGNES_INCR" -gt $MAX_NBLIGNES_INCR ]; then + NBLIGNES_INCR=$MAX_NBLIGNES_INCR + fi + LISTING_INCR="$( printf "%s\n%s (%dj)\t%s" "$LISTING_INCR" "$REP" "$NBLIGNES_INCR" "$( cat "$REP/backups" | egrep "^[0-9]+[[:space:]]+incr" | tail -n $MAX_NBLIGNES_INCR | somme_ligne )" )" + + +done + +echo "$LISTING_FULL" +echo +echo "$LISTING_INCR" + + diff --git a/oldies/script_ml-gestion-abonne.sh b/oldies/script_ml-gestion-abonne.sh new file mode 100755 index 0000000..8ac79c5 --- /dev/null +++ b/oldies/script_ml-gestion-abonne.sh @@ -0,0 +1,177 @@ +#!/bin/sh + +# Ce script sert à gérer les abonnements d'une adresse email +# +# exemple d'utilisation : +# - supprimer une adresse de toutes les mailings-list (suppression d'un compte) +# - ajouter interactivement une adresse à certaines ML avec un choix par +# défaut (salaries, ...) +# +# note: dans l'autre sens (ie. pour gérer une mailing-list donnée), il vaut +# mieux passer par phpldapadmin ou similaire, c'est plus pratique. +# +# Known bug: ne pas utiliser avec les mailings-lists ou adresses emails +# dont le nom contient un espace. + + +# Inclusion de la conf. + fonctions de base +. ./lib_gestion-mailinglists.sh + +# Initialisation des variables "globales" +MODE_INTERACTIF="0" +MODE_LISTING="0" +AJOUTS="" +SUPPRESSIONS="" +LOGFILE=$( mktemp ) +LISTING_MAILING_LISTS=$( afficher_listing_mailinglists ) + + + +# Fonctions +# affiche le message d'aide +usage() { +cat <&2 + else + rm -f "$LOGFILE" + fi + RETOUR="$1" + fi + exit "$RETOUR" +} + +# Début du code +# gestion des options de lancement +while getopts a:r:ihl f; do + case $f in + 'a') + AJOUTS=$( echo $AJOUTS $OPTARG ) + ;; + + 'r') + SUPPRESSIONS=$( echo $SUPPRESSIONS $OPTARG ) + ;; + + 'i') + MODE_INTERACTIF=1 + ;; + + 'l') + MODE_LISTING=1 + ;; + + 'h') + usage + terminaison 0 + ;; + + \?) + usage >&2 + terminaison 1 + ;; + esac +done +shift $( expr $OPTIND - 1 ) +MAIL="$1" + +# Petite vérif. +if [ "$MAIL" = "" ]; then + echo "ERREUR: aucune adresse email fournie." >&2 + usage + terminaison 1 +fi + +# Mode listing +if [ "$MODE_LISTING" -gt 0 ]; then + afficher_abonnements_en_cours "$MAIL" + terminaison 0 +fi + +# Les mailings-lists demandées existent-elles ? +TMP=0 +for ML in $AJOUTS $SUPPRESSIONS; do + if [ $( printf "%s\nALL\n" "$LISTING_MAILING_LISTS" | egrep -c "^$ML$" ) -ne 1 ]; then + echo "ERREUR: la mailing-list ne semble pas exister : $ML" >&2 + TMP=1 + fi +done +test "$TMP" -eq 0 || terminaison 1 + +# Construction de la liste finale des abonnements +if [ $( echo "$SUPPRESSIONS" | grep -wc "ALL" ) -gt 0 ]; then + # Suppression de tous les abonnements (paramètre "-r ALL") + SUPPRESSIONS=$( afficher_abonnements_en_cours "$MAIL" ) +fi +LISTE_FINALE=$( (afficher_abonnements_en_cours "$MAIL" | grep -wFv "$( echo "$SUPPRESSIONS" | sed 's/ \+/\n/g' )" ; echo "$AJOUTS" | sed 's/ \+/\n/g') | grep -v "^$" | sort -u ) + +# Entrée dans le "mode interactif" +BOUCLE_INTERACTIVE=$MODE_INTERACTIF # simple copie cosmétique, histoire de garder le paramètre jusqu'au bout (sait-on jamais :) +while [ "$BOUCLE_INTERACTIVE" -eq 1 ]; do + # Listing des mailing-lists disponibles + echo "Listing des mailing-lists : " + printf "%s\n" "$LISTING_MAILING_LISTS" | sed 's/^/ /' + + # Prompt pour la modification du listing + LISTE_FINALE=$( echo $LISTE_FINALE ) # ça permet de convertir facilement en une liste mono-ligne :) + printf "Indiquer les listes auxquelles l'email %s doit être abonné, ligne vide pour terminer\n(. pour ignorer la proposition et annuler les entrées précédentes)\n[%s]\n" "$MAIL" "$LISTE_FINALE" + LISTE_USER=$( while read LINE; do if [ "$LINE" = "" ]; then exit 0; else echo "$LINE"; fi; done ) + + # écrasement de LISTE_FINALE si l'utilisateur a entré qqchose + if [ "$LISTE_USER" != "" ]; then + LISTE_FINALE="" + fi + + # On vérifie chaque entrée (un peu redondant avec la boucle de vérif. précédente) + BOUCLE_INTERACTIVE=0 + for ML in $LISTE_USER; do + # Si c'est un "." qui a été rentré, on efface la liste finale + if [ "$ML" = "." ]; then + LISTE_FINALE="" + + # sinon, on vérifie simplement que la mailing-list existe + elif [ $( printf "%s\n" "$LISTING_MAILING_LISTS" | egrep -c "^$ML$" ) -ne 1 ]; then + # Si elle n'existe pas: nouveau tour gratuit + echo "ERREUR: la mailing-list ne semble pas exister : $ML" >&2 + BOUCLE_INTERACTIVE=1 + else + # On concatène (astuce avec echo pour enlever les espaces inutiles) + LISTE_FINALE=$( echo $LISTE_FINALE $ML ) + fi + done +done + + +# - les suppressions +for ML in $( afficher_abonnements_en_cours "$MAIL" | grep -wFv "$( echo "$LISTE_FINALE" | sed 's/ \+/\n/g' )" ); do + printf "Suppression de %s de la mailing-list %s.\n" "$MAIL" "$ML" + supprimer_abonnement "$MAIL" "$ML" >"$LOGFILE" 2>&1 || terminaison 1 +done + +# - les créations d'abonnement +for ML in $( echo "$LISTE_FINALE" | sed 's/ \+/\n/g' | grep -wFv "$( afficher_abonnements_en_cours "$MAIL" )" ); do + printf "Ajout de %s à la mailing-list %s.\n" "$MAIL" "$ML" + creer_abonnement "$MAIL" "$ML" >"$LOGFILE" 2>&1 || terminaison 1 +done + + +# Fin du script - nettoyage +terminaison 0 + diff --git a/oldies/script_ml-gestion-mailinglist.sh b/oldies/script_ml-gestion-mailinglist.sh new file mode 100755 index 0000000..6fb7182 --- /dev/null +++ b/oldies/script_ml-gestion-mailinglist.sh @@ -0,0 +1,214 @@ +#!/bin/sh + +# Ce script sert à créer/supprimer une mailing-list +# +# exemple d'utilisation : +# - créer une mailing-list et lui ajouter des abonnés, +# - retirer des abonnés d'une mailing-list, +# - supprimer une mailing-list +# +# note: dans l'autre sens (ie. gérer les abonnements d'une adresse donnée), +# il existe le script_ml-gestion-abonne.sh +# +# Known bug: ne pas utiliser avec les mailings-lists ou adresses emails +# dont le nom contient un espace. + + +# Inclusion de la conf. + fonctions de base +. ./lib_gestion-mailinglists.sh + +# Initialisation des variables "globales" +MODE_INTERACTIF="0" +MODE_LISTING_ABONNES="0" +CREATION_SUPPRESSION="0" # 0: neutre, -1: suppression, 1: creation +AJOUTS="" +SUPPRESSIONS="" +LOGFILE=$( mktemp ) + + + +# Fonctions +# affiche le message d'aide +usage() { +cat <&2 + else + rm -f "$LOGFILE" + fi + RETOUR="$1" + fi + exit "$RETOUR" +} + +# Début du code +# gestion des options de lancement +while getopts cda:r:ihlL f; do + case $f in + 'c') + CREATION_SUPPRESSION=1 + ;; + + 'd') + CREATION_SUPPRESSION=-1 + ;; + + 'a') + AJOUTS=$( echo $AJOUTS $OPTARG ) + ;; + + 'r') + SUPPRESSIONS=$( echo $SUPPRESSIONS $OPTARG ) + ;; + + 'i') + MODE_INTERACTIF=1 + ;; + + 'l') + MODE_LISTING_ABONNES=1 + ;; + + 'L') + afficher_listing_mailinglists + terminaison 0 + ;; + + 'h') + usage + terminaison 0 + ;; + + \?) + usage >&2 + terminaison 1 + ;; + esac +done +shift $( expr $OPTIND - 1 ) +MAILINGLIST="$1" + +# Petite vérif. +if [ "$MAILINGLIST" = "" ]; then + echo "ERREUR: aucune mailing-list n'a été indiquée." >&2 + usage + terminaison 1 +fi + +# Mode listing des abonnes d'une mailing-linst +if [ "$MODE_LISTING_ABONNES" -gt 0 ]; then + # On vérifie quand même que la mailing-list existe... + if [ $( afficher_listing_mailinglists | grep -wc "^$MAILINGLIST$" ) -ne 1 ]; then + echo "ERREUR: mailing-list inexistante." >&2 + terminaison 1 + fi + + # Listing des abonnés de la mailing-list + afficher_abonnes_mailinglist "$MAILINGLIST" + terminaison 0 +fi + +# La mailing-list demandée existe-elle ? +if [ $( printf "%s\n" "$( afficher_listing_mailinglists )" | egrep -c "^$MAILINGLIST$" ) -ne 1 ]; then + # Si elle n'existe pas, doit-on la créer ? + if [ $CREATION_SUPPRESSION -lt 1 ]; then + echo "ERREUR: la mailing-list ne semble pas exister : $MAILINGLIST" >&2 + terminaison 1 + else + # On crée la mailing-list + printf "Création de la mailing-list..." + if creer_mailinglist "$MAILINGLIST" >"$LOGFILE" 2>&1; then + printf " [OK]\n" + else + printf "\nProblèmes à la création de la mailing-list. Cf log.\n" >&2 + terminaison 1 + fi + fi +else + # Si elle existe, doit-on la supprimer ? + if [ "$CREATION_SUPPRESSION" -lt 0 ]; then + # On la supprime et on arrête là le script + printf "Suppression de la mailing-list..." + if supprimer_mailinglist "$MAILINGLIST" >"$LOGFILE" 2>&1; then + printf "[OK]\n"; + terminaison 0 + else + printf "\nProblèmes à la suppression de la mailing-list. Cf log.\n" >&2 + terminaison 1 + fi + fi +fi + +# Construction de la liste finale des abonnements +if [ $( echo "$SUPPRESSIONS" | grep -wc "ALL" ) -gt 0 ]; then + # Suppression de tous les abonnés (paramètre "-r ALL") + SUPPRESSIONS=$( afficher_abonnes_mailinglist "$MAILINGLIST" ) +fi +LISTE_FINALE=$( (afficher_abonnes_mailinglist "$MAILINGLIST" | grep -wFv "$( echo "$SUPPRESSIONS" | sed 's/ \+/\n/g' )" ; echo "$AJOUTS" | sed 's/ \+/\n/g') | grep -v "^$" | sort -u ) + +# Entrée dans le "mode interactif" +BOUCLE_INTERACTIVE=$MODE_INTERACTIF # simple copie cosmétique, histoire de garder le paramètre jusqu'au bout (sait-on jamais :) +while [ "$BOUCLE_INTERACTIVE" -eq 1 ]; do + # Prompt pour la modification du listing + LISTE_FINALE=$( echo $LISTE_FINALE ) # ça permet de convertir facilement en une liste mono-ligne :) + printf "Indiquer les emails qui seront abonnés à la liste '%s', ligne vide pour terminer\n(. pour ignorer la proposition et annuler les entrées précédentes)\n[%s]\n" "$MAILINGLIST" "$LISTE_FINALE" + LISTE_USER=$( while read LINE; do if [ "$LINE" = "" ]; then exit 0; else echo "$LINE"; fi; done ) + + # écrasement de LISTE_FINALE si l'utilisateur a entré qqchose + if [ "$LISTE_USER" != "" ]; then + LISTE_FINALE="" + fi + + # On vérifie chaque entrée (un peu redondant avec la boucle de vérif. précédente) + BOUCLE_INTERACTIVE=0 + for MAIL in $LISTE_USER; do + # Si c'est un "." qui a été rentré, on efface la liste finale + if [ "$MAIL" = "." ]; then + LISTE_FINALE="" + else + # sinon, on concatène (astuce avec echo pour enlever les espaces inutiles) + LISTE_FINALE=$( echo $LISTE_FINALE $MAIL ) + fi + done +done + + +# - les suppressions +for MAIL in $( afficher_abonnes_mailinglist "$MAILINGLIST" | grep -wFv "$( echo "$LISTE_FINALE" | sed 's/ \+/\n/g' )" ); do + printf "Suppression de %s de la mailing-list %s.\n" "$MAIL" "$MAILINGLIST" + supprimer_abonnement "$MAIL" "$MAILINGLIST" >"$LOGFILE" 2>&1 || terminaison 1 +done + +# - les créations d'abonnement +for MAIL in $( echo "$LISTE_FINALE" | sed 's/ \+/\n/g' | grep -wFv "$( afficher_abonnes_mailinglist "$MAILINGLIST" )" ); do + printf "Ajout de %s à la mailing-list %s.\n" "$MAIL" "$MAILINGLIST" + creer_abonnement "$MAIL" "$MAILINGLIST" >"$LOGFILE" 2>&1 || terminaison 1 +done + + +# Fin du script - nettoyage +terminaison 0 + diff --git a/oldies/script_multi-instance-postgresql.sh b/oldies/script_multi-instance-postgresql.sh new file mode 100755 index 0000000..65c6e21 --- /dev/null +++ b/oldies/script_multi-instance-postgresql.sh @@ -0,0 +1,591 @@ +#!/bin/sh + +# Ce script sert à créer ou détruire : +# - une instance PostgreSQL (PGDATA). + +# Il peut également gérer un serveur esclave en définissant la +# variable $ESCLAVE . Dans ce cas là, mieux vaut avoir une authentification +# par clef (les opérations se font par ssh) +# +# Attention, ce script affiche les identifiants à l'écran. + +# Prérequis : +# - PostgreSQL +# Si utilisation d'un esclave : +# - une authentification pour l'utilisateur root local vers root@$ESCLAVE par clef, +# - une authentification pour l'utilisateur postgres local vers postgres@$ESCLAVE par clef. + +# Trucs à nettoyer (si quelque chose part en vrille, ou simplement +# pour désinstaller ): +# - TODO + +# Version de PostgreSQL : 9.1 seule testée +VERSION_POSTGRESQL="9.1" +# Mettre ci-dessous le nom d'hôte ou l'IP du serveur esclave +# (utilisé par la config PG + les connexions SSH pour l'exécution +# des commandes distantes de ce script) +ESCLAVE="" +# idem pour le maître (vu depuis l'esclave en cas de réseau privé) +# (utilisé pour la config PG) +MAITRE="" + +# Initialisation des variables globales +MODE_CREATION=0 +MODE_DESTRUCTION=0 +POSTGRESQL_REPLICATION_USER_NAME="repliquser" +POSTGRESQL_LOCALE="fr_FR.utf8" +POSTGRESQL_PORT="" + +# Par défaut, on arrête le script à la première erreur non "catchée" +set -e + +# On s'exécute dans un dossier accessible à l'utilisateur postgres +cd /tmp + +# Fonctions +# affiche le message d'aide +usage() { +cat < -m ] [ -p ] + $0 -d cluster-name [ -e -m ] + $0 -h + + -c xxx : création d'une instance/cluster nommée 'xxx' + -d xxx : destruction de l'instance nommée 'xxx' + + -p nnn : numéro de port à affecter au nouveau cluster (par défaut, 'auto') + +# Ce script peut générer la configuration nécessaire au streaming replication + -e esclave : nom d'hôte ou IP de l'esclave + -m maitre : nom d'hôte ou IP du serveur maître + + -h : ce message d'aide +EOF +} + +# Arguments +# $1 : IPv4, IPv6 ou nom d'hôte +# Cette fonction suffixe d'un /32 ou /128 +# la chaîne si celle-ci est une adresse IP +add_mask_ip() { + test -n "$1" || exit 1 + + if [ $( echo "$1" | egrep -c "^([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}$" ) -gt 0 ]; then + printf "$1/32" + elif [ $( echo "$1" | egrep -c "^[[:xdigit:]:]*$" ) -gt 0 ]; then + printf "$1/128" + else + printf "$1" + fi +} + +# Arguments +# $1 : IP esclave +# $2 : version PostgreSQL +# $3 : nom de l'instance +generate_patch_postgresqlconf_master() { + test -n "$1" && test -n "$2" && test -n "$3" || exit 1 + cat </dev/null 2>&1; then + case "$BEGINNING" in + "ERREUR"|"ERROR") + tput setaf 1;; + "WARN"|"WARNING") + tput setaf 3;; + "INFO"|"DEBUG") + tput setaf 2;; + esac + printf "%s" "$BEGINNING" + tput op + printf "%s\n" "$( printf "%s" "$1" | sed '1 s/^[A-Z]\+:/:/' )" + else + printf "%s\n" "$1" + fi +} + + +# Début du code +# gestion des options de lancement +while getopts c:d:e:m:p:h f; do + case $f in + 'c') + MODE_CREATION=1 + NOM_INSTANCE="$OPTARG" + ;; + + 'd') + MODE_DESTRUCTION=1 + NOM_INSTANCE="$OPTARG" + ;; + + 'e') + ESCLAVE="$OPTARG" + ;; + + 'm') + MAITRE="$OPTARG" + ;; + + 'p') + if [ "$OPTARG" = "auto" ]; then + unset POSTGRESQL_PORT + else + POSTGRESQL_PORT="$( printf "%d" "$OPTARG" )" + fi + ;; + + 'h') + usage + exit 0 + ;; + + \?) + usage >&2 + exit 1 + ;; + esac +done +#(code inutile, mais que je garde parce qu'on ne sait jamais) +#shift $( expr $OPTIND - 1 ) +#DATA="$1" +if [ -n "$MAITRE" ] && [ -n "$ESCLAVE" ]; then + MAITRE_WITH_MASK=$( add_mask_ip "$MAITRE" ) + ESCLAVE_WITH_MASK=$( add_mask_ip "$ESCLAVE" ) +fi + +# Petite vérif. +case $(( $MODE_CREATION + $MODE_DESTRUCTION )) in + '0') + fancylog "ERREUR: veuillez choisir entre création et destruction." >&2 + usage >&2 + exit 1 + ;; + '2') + fancylog "ERREUR: tu veux créer et détruire en même temps, petit malin ?" >&2 + exit 1 + ;; +esac + +# Petites vérifications préliminaires : +fancylog "INFO: petites vérifications préliminaires..." +# - vérifications sur le nom du clustername fourni +OLD_LC_ALL="$LC_ALL" +export LC_ALL=C +export LANG=C +if [ $( printf "$NOM_INSTANCE" | egrep -c "^[a-z][a-z0-9_]{0,14}$" ) -ne 1 ]; then + fancylog "ERREUR: clustername vide ou contenant des caractères interdits : regexp : [a-z][a-z0-9_]{0,14}" >&2 + exit 1 +fi +export LC_ALL="$OLD_LC_ALL" +export LANG="$OLD_LC_ALL" +# - est-ce que l'auth. SSH par clef fonctionne pour root et postgres ? +if [ -n "$ESCLAVE" ]; then + # - vérification de l'auth. par clefs SSH + if ! ssh -o BatchMode=yes root@$ESCLAVE /bin/true; then + fancylog "ERREUR: auth. par clef SSH non configurée pour l'utilisateur 'root'." + exit 1 + fi + if ! su -c "ssh -o BatchMode=yes postgres@$ESCLAVE /bin/true" postgres; then + fancylog "ERREUR: auth. par clef SSH non configurée pour l'utilisateur 'postgres'." + exit 1 + fi + + # - vérification de la présence de $MAITRE + if [ ! -n "$MAITRE" ]; then + fancylog "ERREUR: serveur esclave indiqué, mais pas de serveur maître (option -m)." >&2 + exit 1 + fi +fi + +# - est-ce qu'on est bien sur une Debian 6 ou 7 +# (c'est surtout pour éviter les mauvaises surprises, ce script n'ayant pas été testé ailleurs) +if [ ! -f "/etc/debian_version" ] || [ $( egrep -c "^(6.|7.)" /etc/debian_version ) -ne 1 ]; then + fancylog "ERREUR: mauvaise version de Debian détectée. Arrêt par prudence. Vérifiez le code de ce script avant de forcer." >&2 + exit 1 +fi +if [ -n "$ESCLAVE" ] && [ "$( ssh root@$ESCLAVE 'egrep -c "^(6.|7.)" /etc/debian_version' )" -ne 1 ]; then + fancylog "ERREUR: ESCLAVE: mauvaise version de Debian détectée. Arrêt par prudence. Vérifiez le code de ce script avant de forcer." >&2 + exit 1 +fi + +# - est-ce que la version attendue de PostgreSQL est bien installée ? +if ! dpkg -s "postgresql-$VERSION_POSTGRESQL" >/dev/null 2>&1; then + fancylog "ERREUR: PostgreSQL $VERSION_POSTGRESQL ne semble pas installée." >&2 + exit 1 +fi +if [ -n "$ESCLAVE" ] && ! ssh root@$ESCLAVE dpkg -s "postgresql-$VERSION_POSTGRESQL" >/dev/null 2>&1; then + fancylog "ERREUR: PostgreSQL $VERSION_POSTGRESQL ne semble pas installée." >&2 + exit 1 +fi + +# Fin des vérifications +fancylog "INFO: fin des vérifications. Lancement des opérations." + + +if [ "$MODE_CREATION" -eq 1 ]; then + POSTGRESQL_PASSWORD=$( dd if=/dev/random 2>/dev/null bs=1 count=10 status=noxfer | base64 | sed 's#[/=]##g' ) + POSTGRESQL_REPLICATION_PASSWORD=$( dd if=/dev/random 2>/dev/null bs=1 count=20 status=noxfer | base64 | sed 's#[/=]##g' ) + # Création de l'instance dédiée + fancylog "INFO: création du cluster PG primaire..." + if [ -z "$POSTGRESQL_PORT" ]; then + pg_createcluster --locale=$POSTGRESQL_LOCALE --start-conf=auto "$VERSION_POSTGRESQL" "$NOM_INSTANCE" + # Détermination du port généré + # TODO: récupérer ça via pg_lsclusters serait plus "propre" + POSTGRESQL_PORT=$( grep "^port" /etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/postgresql.conf | sed 's/^port[[:space:]]*=[[:space:]]*\([0-9]\+\).*$/\1/' ) + else + pg_createcluster --locale=$POSTGRESQL_LOCALE --start-conf=auto --port "$POSTGRESQL_PORT" "$VERSION_POSTGRESQL" "$NOM_INSTANCE" + fi + fancylog "INFO: modification du pg_hba.conf..." + if ! generate_patch_postgresql_pghbaconf "$NOM_INSTANCE" | patch -s --dry-run /etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/pg_hba.conf; then + fancylog "ERREUR: modification du fichier pg_hba.conf en échec. Arrêt." + exit 1 + fi + generate_patch_postgresql_pghbaconf "$NOM_INSTANCE" | patch -s /etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/pg_hba.conf + + fancylog "INFO: démarrage de l'instance PostgreSQL..." + pg_ctlcluster "$VERSION_POSTGRESQL" "$NOM_INSTANCE" start + + # Lancement du script fourre-tout + fancylog "INFO: création de l'utilisateur et de la base de données, et affinage des droits d'accès..." + generate_script_postgresql_creation_db_et_user "$NOM_INSTANCE" "$POSTGRESQL_PASSWORD" "$POSTGRESQL_REPLICATION_USER_NAME" "$POSTGRESQL_REPLICATION_PASSWORD" | su -c "psql -p $POSTGRESQL_PORT -v ON_ERROR_STOP=1" postgres + + if [ -n "$ESCLAVE" ]; then + fancylog "INFO: création de l'utilisateur de réplication..." + generate_script_postgresql_creation_replication_user "$POSTGRESQL_REPLICATION_USER_NAME" "$POSTGRESQL_REPLICATION_PASSWORD" | su -c "psql -p $POSTGRESQL_PORT -v ON_ERROR_STOP=1" postgres + + # configuration en tant que maître + fancylog "INFO: modification de la configuration BDD de l'instance primaire..." + if ! generate_patch_postgresqlconf_master "$ESCLAVE" "$VERSION_POSTGRESQL" "$NOM_INSTANCE" | patch -s --dry-run /etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/postgresql.conf; then + fancylog "ERREUR: modification du fichier postgresql.conf en échec. Arrêt." + exit 1 + fi + generate_patch_postgresqlconf_master "$ESCLAVE" "$VERSION_POSTGRESQL" "$NOM_INSTANCE" | patch -s /etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/postgresql.conf + # On rajoute les lignes pour la connexion streaming replication dans le pg_hba.conf + echo "host replication $POSTGRESQL_REPLICATION_USER_NAME $ESCLAVE_WITH_MASK md5" >>/etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/pg_hba.conf + echo "host replication $POSTGRESQL_REPLICATION_USER_NAME $MAITRE_WITH_MASK md5" >>/etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/pg_hba.conf + + # Création sur l'esclave + # Note: on commence par créer l'arborescence de l'esclave pour + # avoir le répertoire de destination des archives logs + # le plus tôt possible (en tout cas, avant le pg_stop_backup() + # qui envoie forcément un WAL) + fancylog "INFO: création du cluster PG secondaire..." + ssh "root@$ESCLAVE" "cd /tmp; pg_createcluster --locale='$POSTGRESQL_LOCALE' -p '$POSTGRESQL_PORT' --start-conf=auto '$VERSION_POSTGRESQL' '$NOM_INSTANCE'" + fancylog "INFO: création du dossier de réception des archives logs et arret du backup..." + su -c "mkdir '/var/lib/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/archives_from_master'" postgres + su -c "ssh postgres@$ESCLAVE mkdir '/var/lib/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/archives_from_master'" postgres + + fancylog "INFO: redémarrage du serveur primaire..." + pg_ctlcluster "$VERSION_POSTGRESQL" "$NOM_INSTANCE" restart + + # rsync du PGDATA vers l'esclave + fancylog "INFO: écrasement du PGDATA secondaire par celui de l'instance primaire..." + echo "SELECT pg_start_backup('script_mi_pg', true);" | su -c "psql -p $POSTGRESQL_PORT -v ON_ERROR_STOP=1" postgres + # on attend un peu, il y a parfois des fichiers WAL qui "vanished" pendant le rsync + sleep 1 + # On exclut : + # - postmaster.pid : raison évidente :) + # - postmaster.opts : a priori, le contenu est identique mais par prudence... + # - server.key/server.crt : rsync génère une erreur sur la date de modification des symlinks :-/ + # - recovery.* : le recovery.done du maitre référence l'esclave, et vice versa pour le recovery.conf de l'esclave + # - archives_from_master : cela écraserait tout éventuel WAL déjà envoyé + # - lost+found : au cas où la partition existe déjà (pg_createcluster se bloque mais ça permet de récupérer cette ligne de commande ailleurs :) + # A étudier : pas de --delete ? + # test -c car problème de synchro bizarre + su -c "rsync -aHc --exclude=/postmaster.pid --exclude=/postmaster.opts --exclude=/server.key --exclude=/server.crt --exclude=/recovery.conf --exclude=/recovery.done --exclude=/archives_from_master --exclude=lost+found /var/lib/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/ postgres@$ESCLAVE:/var/lib/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/" postgres + echo "SELECT pg_stop_backup();" | su -c "psql -p $POSTGRESQL_PORT -v ON_ERROR_STOP=1" postgres + + # configuration de l'esclave + fancylog "INFO: configuration de l'instance PG secondaire..." + if ! ssh root@$ESCLAVE dpkg -s "postgresql-contrib-$VERSION_POSTGRESQL" >/dev/null 2>&1; then + fancylog "WARNING: Le paquet postgresql-contrib-$VERSION_POSTGRESQL ne semble pas installé sur le serveur esclave, archive_cleanup_command sera désactivé." >&2 + fancylog "NOTICE: cf fichier /var/lib/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/recovery.conf en cas d'installation après-coup." >&2 + ARCHIVE_CLEANUP_COMMAND="" + else + # TODO: à rendre plus portable ? + ARCHIVE_CLEANUP_COMMAND="/usr/lib/postgresql/$VERSION_POSTGRESQL/bin/pg_archivecleanup" + fi + generate_file_postgresqlrecoveryconf_slave "$MAITRE" "$POSTGRESQL_PORT" "$POSTGRESQL_REPLICATION_USER_NAME" "$POSTGRESQL_REPLICATION_PASSWORD" "$VERSION_POSTGRESQL" "$NOM_INSTANCE" "$ARCHIVE_CLEANUP_COMMAND" | su -c "ssh postgres@$ESCLAVE 'cat - >/var/lib/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/recovery.conf'" postgres + generate_file_postgresqlrecoveryconf_slave "$ESCLAVE" "$POSTGRESQL_PORT" "$POSTGRESQL_REPLICATION_USER_NAME" "$POSTGRESQL_REPLICATION_PASSWORD" "$VERSION_POSTGRESQL" "$NOM_INSTANCE" "$ARCHIVE_CLEANUP_COMMAND" | su -c "cat - >/var/lib/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/recovery.done" postgres + generate_patch_postgresqlconf_slave | ssh "root@$ESCLAVE" patch -s /etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/postgresql.conf + # (note: même fichier pg_hba.conf pour tout le monde, homogénéisation avec peu de risques il me semble) + scp -q /etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/pg_hba.conf root@$ESCLAVE:/etc/postgresql/$VERSION_POSTGRESQL/$NOM_INSTANCE/pg_hba.conf + + # démarrage des instances maître et esclave + fancylog "INFO: démarrage de l'instance PostgreSQL esclave..." + ssh root@$ESCLAVE pg_ctlcluster "$VERSION_POSTGRESQL" "$NOM_INSTANCE" start + + # Vérification de la réplication + # TODO (via numéro de transaction (requête) ? processus/connexion ?) + fi + + # Fin + fancylog "INFO: Création terminée. Instance PostgreSQL allumée." + fancylog "INFO: pour mémo :" + fancylog "INFO: BDD: $NOM_INSTANCE, port: $POSTGRESQL_PORT, login: $NOM_INSTANCE, mdp: $POSTGRESQL_PASSWORD" + TMP="$MAITRE" + if [ -z "$MAITRE" ]; then + TMP="localhost" + fi + fancylog "INFO: pgpass: $TMP:$POSTGRESQL_PORT:$NOM_INSTANCE:$NOM_INSTANCE:$POSTGRESQL_PASSWORD" +fi + + + +if [ "$MODE_DESTRUCTION" -eq 1 ]; then + fancylog "INFO: suppression de l'instance locale..." + # Note : en guise de garde-fou, on ne met pas l'option --stop + pg_dropcluster "$VERSION_POSTGRESQL" "$NOM_INSTANCE" + + if [ -n "$ESCLAVE" ]; then + fancylog "INFO: suppression de l'instance esclave..." + ssh root@$ESCLAVE pg_dropcluster "$VERSION_POSTGRESQL" "$NOM_INSTANCE" + fi +fi + + diff --git a/oldies/script_multi-instance-tomcat.sh b/oldies/script_multi-instance-tomcat.sh new file mode 100755 index 0000000..12fa0b1 --- /dev/null +++ b/oldies/script_multi-instance-tomcat.sh @@ -0,0 +1,453 @@ +#!/bin/sh + +# Ce script sert à créer ou détruire une instance Tomcat +# en créant un CATALINA_BASE indépendant. + +# L'usage habituel se fait sur une Debian 7 "Wheezy" avec +# tomcat, libapache2-mod-jk et apache2 installé. + +# Prérequis : +# - Debian Wheezy (Squeeze non testée) +# - tomcat7 (6 non testée) +# - libapache2-mod-jk avec le workers.properties du module + +# Trucs à nettoyer (si quelque chose part en vrille, ou simplement +# pour désinstaller ): +# - supprimer tout le répertoire REP_TOMCAT_MULTIINSTANCE +# - supprimer /etc/default/tomcatN_XXX +# - supprimer /etc/init.d/tomcatN_XXX +# - supprimer les utilisateurs tomcatN_YYYY +# - nettoyer les clusters PostgreSQL + +# Version de Tomcat : 6 ou 7 +# TODO : voir si on peut le passer en paramètre pour gérer +# Tomcat 6 & 7 sur la même machine +VERSION_TOMCAT="7" +# Quelques constantes internes +MAX_INSTANCES=999 +START_RANGE_TOMCATUID=8000 +START_RANGE_TOMCAT_PORT_SYS=15000 +START_RANGE_TOMCAT_PORT_HTTP=18000 +START_RANGE_TOMCAT_PORT_AJP=19000 + +# Initialisation des variables globales +MODE_CREATION=0 +MODE_DESTRUCTION=0 +TOMCAT_ENABLE_SHUTDOWN_PORT="" +OPTION_WORKERS_PROPERTIES="" +OPTION_VHOST_APACHE_SERVERNAME="" +NB_CHIFFRES_DANS_NUM_INSTANCE=$( printf "%d" "$MAX_INSTANCES" | wc -c ) +REP_TOMCAT_MULTIINSTANCE="/var/lib/tomcat$VERSION_TOMCAT-multiinstances" +# On récupère également le nom de l'utilisateur et du groupe de Tomcat +if [ ! -f /etc/default/tomcat$VERSION_TOMCAT ]; then + echo "ERREUR: /etc/default/tomcat$VERSION_TOMCAT inaccessible." >&2 + exit 1 +fi +. /etc/default/tomcat$VERSION_TOMCAT + +# Par défaut, on arrête le script à la première erreur non "catchée" +set -e + +# Fonctions + +# Arguments +# $1 : Version de Tomcat +# $2 : nom du worker +# $3 : port AJP du worker +ajout_worker_properties() { + test -n "$1" && test -n "$2" && test -n "$3" || exit 1 + # On se fiche un peu de la version de Tomcat, en fait :) + case "$1" in + 6|7) + cat <&2 + exit 1 + ;; + esac +} + +# Arguments +# $1 : Version de Tomcat +# $2 : port système (d'habitude 8005) +# $3 : port connecteur HTTP (8080, d'habitude) +# $4 : port connecteur AJP (8009, d'habitude) +generate_patch_tomcat_server_xml() { + test -n "$1" && test -n "$2" && test -n "$3" && test -n "$4" && test -n "$5" || exit 1 + case "$1" in + 6|7) + generate_patch_tomcat_server_xml_6 "$2" "$3" "$4" "$5" + ;; + *) + echo "ERREUR: version de Tomcat non-gérée." >&2 + exit 1 + ;; + esac +} + +# Arguments +# $1 : port système (d'habitude 8005) +# $2 : port connecteur HTTP (8080, d'habitude) +# $3 : port connecteur AJP (8009, d'habitude) +generate_patch_tomcat_server_xml_6() { + local NOM_WORKER TOMCAT_PORT_SYS TOMCAT_PORT_HTTP TOMCAT_PORT_AJP + test -n "$1" && test -n "$2" && test -n "$3" && test -n "$4" || exit 1 + NOM_WORKER="$1" + TOMCAT_PORT_SYS="$2" + TOMCAT_PORT_HTTP="$3" + TOMCAT_PORT_AJP="$4" + cat < +- ++ + +@@ -69,10 +69,12 @@ + APR (HTTP/AJP) Connector: /docs/apr.html + Define a non-SSL HTTP/1.1 Connector on port 8080 + --> +- ++ --> + + + + +- ++ + + + +- ++ + +