Skip to content

Instantly share code, notes, and snippets.

@ninjix
Last active April 19, 2017 18:57
Show Gist options
  • Save ninjix/b58ef5eaa044d009e8b9 to your computer and use it in GitHub Desktop.
Save ninjix/b58ef5eaa044d009e8b9 to your computer and use it in GitHub Desktop.
Simple script for monitoring Apache2 mod_status pages. Designed for Zabbix usage.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Quick way to monitor Apache mod_status. Designed for use with Zabbix.
"""
import sys
import urllib2
import argparse
def get_url(url):
""" Uses urllib2 to request Apache mod_status """
try:
conn = urllib2.urlopen(url)
response = conn.read()
conn.close()
return response
except urllib2.HTTPError:
print "Error getting URL"
def parse_scoreboard(scoreboard):
""" Parses scoreboard """
keys = {
'_': 'WaitingForConnection',
'S': 'StartingUp',
'R': 'ReadingRequest',
'W': 'SendingReply',
'K': 'KeepaliveRead',
'D': 'DNSLookup',
'C': 'ClosingConnection',
'L': 'Logging',
'G': 'GracefullyFinishing',
'I': 'Idle',
'.': 'OpenSlot'
}
scores = {}
for score in scoreboard:
if score in keys:
if score in scores:
scores[keys[score]] += 1
else:
scores[keys[score]] = 1
return scores
def get_status(url=None):
""" Returns an Apache performance stat or list all of them """
if url is None:
url = 'http://localhost/server-status'
stats_text = get_url('{}?auto'.format(url))
status = {}
for line in stats_text.split("\n"):
if ':' in line:
key, value = line.split(':')
if key == 'Scoreboard':
for sk, sv in parse_scoreboard(value.strip()).iteritems():
status[sk] = sv
else:
status[key.strip().replace(' ', '_')] = float(value.strip())
return status
def output_status(status, stat=None):
""" Output function """
if stat in status:
print status[stat]
else:
print
for key, value in status.iteritems():
print "{:<30}{:<20}".format(key, value)
print
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
parser.add_argument('-u', '--url', help='URL to query stats', default='http://localhost/server-status')
parser.add_argument('-s', '--stat', help='Return the value for a specific statistic', default=None)
parser.add_argument('-l', '--list', help='List all available Apache mod_status stats', action='store_true')
args = parser.parse_args()
if args.list:
srv_status = get_status(args.url)
output_status(srv_status, args.stat)
else:
srv_status = get_status(args.url)
output_status(srv_status, stat=args.stat)
@dougiep16
Copy link

dougiep16 commented Apr 19, 2017

Line 44 should be

if keys[score] in scores: instead of if score in scores:

Other than that, this helped me a bunch. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment