Index: trunk/tools/nagios/check_cert |
— | — | @@ -0,0 +1,44 @@ |
| 2 | +#!/usr/bin/python |
| 3 | +import socket |
| 4 | +import ssl |
| 5 | +import time |
| 6 | +import datetime |
| 7 | +import sys |
| 8 | +from optparse import OptionParser |
| 9 | + |
| 10 | +parser = OptionParser(conflict_handler="resolve") |
| 11 | +parser.set_usage("check_cert <hostname> <port> <CAfile>\nExample: check_cert secure.wikimedia.org 443 Equifax_Secure_CA.pem") |
| 12 | +(options, args) = parser.parse_args() |
| 13 | + |
| 14 | +if len(args) != 3: |
| 15 | + parser.error("check_cert requires exactly 3 arguments.\n") |
| 16 | + sys.exit(3) |
| 17 | + |
| 18 | +HOST = args[0] |
| 19 | +PORT = int(args[1]) |
| 20 | + |
| 21 | +sock = socket.socket() |
| 22 | +sock.connect((HOST, PORT)) |
| 23 | + |
| 24 | +# It is required to check for validity to pull the peer cert |
| 25 | +sock = ssl.wrap_socket(sock, |
| 26 | + cert_reqs = ssl.CERT_REQUIRED, |
| 27 | + ca_certs = "/etc/ssl/certs/" + args[2] |
| 28 | + ) |
| 29 | +cert = sock.getpeercert() |
| 30 | + |
| 31 | +expire = datetime.datetime(*time.strptime(cert['notAfter'], "%b %d %H:%M:%S %Y GMT")[0:5]) |
| 32 | +# Send a warning if the cert expires in the next four weeks |
| 33 | +yellow = expire + datetime.timedelta(weeks=-4) |
| 34 | +# Send a critical warning if the cert expires in the next week |
| 35 | +red = expire + datetime.timedelta(weeks=-1) |
| 36 | +EpochSeconds = time.mktime((datetime.datetime.utcnow()).timetuple()) |
| 37 | +now = datetime.datetime.fromtimestamp(EpochSeconds) |
| 38 | + |
| 39 | +if now > yellow: |
| 40 | + if now > red: |
| 41 | + sys.exit(2) |
| 42 | + sys.exit(1) |
| 43 | + |
| 44 | +# Cert is still good |
| 45 | +sys.exit(0) |