一个检查url状态码的小脚本

管理的服务器太多,每次更新程序时,都需要检查某个url是否可以访问。手动curl下状态码或者直接复制到浏览器里看看都不太现实,就写了下面这个小脚本,已经用了好久了,闲着没事,发出来,万一哪天误删了,还可以到博客里找下。

脚本 check_http.py

#!/usr/bin/env python
#coding: utf-8

import httplib
import socket

IP = [
        'peiqiang.net',
        ]

URI = [
        '/archive.html',
       ]


def get_http_status(ip,request_uri,method="HEAD"):
    try:
        conn = httplib.HTTPConnection(ip)
        conn.request(method,request_uri)
        r = conn.getresponse()
        #if method == "GET":
        #    data = r.read()
        status = r.status
    except (httplib.HTTPException, socket.error),e:
        print "Error: %s" % e
    finally:
        conn.close()
    print "Check: http://%s%s %s %s" % (ip,request_uri,method,status)

def check_http():
    for ip in IP:
        print "---%s---" % ip
        for uri in URI:
            get_http_status(ip,uri,method="GET")

if __name__ == '__main__':
    check_http()

执行下脚本

budong@localhost:/tmp$ ./check_http.py
---peiqiang.net---
Check: http://peiqiang.net/archive.html GET 200

参考资料:

python httplib官方文档: https://docs.python.org/2/library/httplib.html