Simple HTTP response code check with python

This quite simple python script can be used to test http response code for given url. Had quite a bit of different random bash scripts that needed this kind of simple but somewhat configurable version of response checking. Might have been able to do this with wget/lynx/etc, but in this case it just seemed faster to write this from a scratch than to check which command line tool would already provide enough those features I finally made here.

#!/usr/bin/env python
import sys, os, getopt, urllib, urllib2

if __name__ == '__main__':
    ok_codes = '200,301,302,304'
    error_codes = '400,403,500,501,502,503,504,505'

    def usage():
        print
        print 'Check http response code.'
        print
        print 'Usage:'
        print ' [options] '
        print
        print 'Options:'
        print '  -k, --ok=          comma separated ok codes (default: %s)' % (ok_codes)
        print '  -e, --error=       comma separated failure codes (default: %s)' % (error_codes)
        print '  -h, --help         print help'
        print
        print 'Return value is set to 0 if code is not in ok or error list.'
        print 'It is set to 1 when in ok list and to -1 when in error list.'
        print '-2 will be returned in case of errors (networking etc).'
        print 'Also, the return value will be printed to stdout.'
        print
        print 'Examples:'
        print ' -k 200,301 http://somewhere.com'
        print '  return value is 1 when reponse is 200 or 301, otherwise 0'
        print ' -e 500,502,503 http://somewhere.com'
        print '  return value is -1 when reponse is 500, 502 or 503, otherwise 0'
        print ' -e 404 -k 200 http://somewhere.com'
        print '  return value is -1 when reponse is 404, 1 when 200, otherwise 0'
        print

    try:
        opts, argv = getopt.gnu_getopt(sys.argv[1:], 'hk:e:', [ 'help', 'ok=', 'error=', ])
    except getopt.GetoptError, err:
        usage()
        sys.exit(1)

    for o, a in opts:
        if o in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif o in ('-k', '--ok'):
            ok_codes = a
        elif o in ('-e', '--error'):
            error_codes = a

    if len(argv) != 1:
        usage()
        sys.exit(1)

    url = argv[0]

    _ok_codes = ok_codes.split(',')
    _error_codes = error_codes.split(',')
    ok_codes = []
    error_codes = []

    try:
        for code in _ok_codes:
            if int(code) < 100:
                raise Exception('')
            ok_codes.append(int(code))
        for code in _error_codes:
            if int(code) < 100:
                raise Exception('')
            error_codes.append(int(code))
    except:
        sys.stderr.write('invalid code: %s\n' % (code))
        sys.exit(-2)

    code = 0

    try:
        req = urllib2.urlopen(url)
        code = req.getcode()
    except urllib2.HTTPError as e:
        code = e.code
    except urllib2.URLError as e:
        sys.stderr.write('invalid url, reason: %s\n' % (e.reason))
        sys.exit(-2)
    except:
        sys.stderr.write('something failed, probably network\n')
        sys.exit(-2)

    if int(code) in error_codes:
        print -1, code
        sys.exit(-1)
    if int(code) in ok_codes:
        print 1, code
        sys.exit(1)

    print 0, code
    sys.exit(0)

Leave a Reply

Your email address will not be published. Required fields are marked *