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

"""
pygetstatus.py
Sebastien Damaye (www.aldeid.com)
2011-01-30


This program opens a socket to a target (web server) and sends HEAD requests for
a list of URLs provided. For each URL, the returned status is displayed (e.g.
200 for OK, 404 for Not Found, ...)

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 <http://www.gnu.org/licenses/>.
"""

import httplib
import socket
import sys
import os
from optparse import OptionParser

class Scan:
    def __init__(self, fileUrls, target, port=80, cookie=''):
        """Perform some checks
        """
        self.fileUrls = fileUrls
        if not os.path.exists(self.fileUrls):
            print ("File %s not found. Please check location." % self.fileUrls)
            sys.exit(2)
        self.target = target
        self.port = port
        self.cookie = cookie

    def getStatus(self):
        """Get the status of requests provided in fileUrls
        """
        urls = open(self.fileUrls, "r")
        if self.cookie:
            params = {}
            headers = {"Cookie": self.cookie}

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((self.target, self.port))

        for iurl in urls:
            url = iurl.split('\n')[0]
            conn = httplib.HTTPConnection(self.target, self.port)
            try:
                if self.cookie:
                    conn.request('HEAD', url, params, headers)
                else:
                    conn.request('HEAD', url)
            except:
                print "***Error: Unable to connect"
            else:
                res = conn.getresponse()
                print "%s;%s" % (url,res.status)
                conn.close

        s.close()
        urls.close()

if __name__ == '__main__':
    usage = "usage: %prog -t <target> -u <fileUrls> [options]"
    parser = OptionParser(usage)
    parser.add_option("-t", "--target", dest="target",
        help="host to connect to (e.g. 192.168.100.14)")
    parser.add_option("-p", "--port", dest="port", default=80,
        help="port to connect to (default: 80)")
    parser.add_option("-u", "--url", dest="fileUrls",
        help="file that contains URLs (one per line)")
    parser.add_option("-c", '--cookie', dest="cookie", default='',
        help="eventual cookie to use (syntax: ""key=value"", e.g. ""PHPSESSID=abcdefghj"")")
    (options, args) = parser.parse_args(sys.argv)
    if not options.target:
        parser.error("Target missing. Use -t <target>.")
    if not options.fileUrls:
        parser.error("URLs file missing. Use -u <fileUrls>.")

    oScan = Scan(options.fileUrls, options.target, options.port, options.cookie)
    oScan.getStatus()
    del oScan