2011年11月6日日曜日

ポートスキャン TCP

#! /usr/bin/env python
#-*- coding: utf-8 -*-
import os
import sys
import time
import socket
import thread
import threading
import optparse


OPEN  = 'o'
CLOSE = 'x'


def check_port(host, port):
    soc = socket.socket()
    soc.settimeout(1)
    try:
        soc.connect((host, port))
    except (socket.timeout, socket.error):
        return CLOSE
    else:
        return OPEN

class Connector(threading.Thread):
    def __init__(self, host, port, *args, **kwds):
        threading.Thread.__init__(self, *args, **kwds)
        self.setDaemon(True)
        self.host = host
        self.port = int(port)
        
    def run(self):
        status = check_port(self.host, self.port)
        sys.stdout.write('{0} {1}'.format(status, self.port) + os.linesep)

def str2ints(word):
    matching = re.match('^(?P\d+)\-(?P\d+)$', word)
    if matching:
        start = int(matching.group('start'))
        end = int(matching.group('end')) + 1
        return range(start, end)
    else:
        try:
            return [int(word)]
        except (TypeError, ValueError), err:
            raise TypeError('{0}: {1}'.format(err, word))

def main():
    parser = optparse.OptionParser()
    opts, args = parser.parse_args()
    
    length = len(args)
    ports = []
    if length < 1:
        parser.error('invalid parameter.')
    elif length == 1:
        ports += range(1025) # well-known
    else:
        for port in args[1:]:
            if port.lower() == 'well-known':
                ports += range(1025)
            else:
                try:
                    ports += str2ints(port)
                except TypeError, err:
                    parser.error(err)
    host = args[0]
    ports = sorted(list(set(ports)))
    for port in ports:
        worker = Connector(host, port)
        worker.start()
    while not time.sleep(2):
        if threading.activeCount() <= 1:
            break
        else:
            sys.stdout.flush()
        

if __name__ == '__main__':
    main()

0 件のコメント:

コメントを投稿