2017年5月

python端口扫描器

学习python网络编程,写了个tcp的端口扫描,单线程,仅仅为了学习而已。

#! /usr/bin/env python
# coding:utf-8
# 端口扫描
import argparse
import socket
import time

def scan(ip, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket.setdefaulttimeout(3)
        status = s.connect_ex((ip, port))
        return status
    except:
        return

def scanport():
    start_time = time.time()
    print u"开放的端口: "
    for port in range(start_port, end_port+1):
        status = scan(target_ip, port)
        if status == 0:
            print "* %s --- open" % str(port)
    print u"扫描结束,耗时: %s s." % (time.time() - start_time)
if __name__ == "__main__":
    parse = argparse.ArgumentParser()
    parse.add_argument("host", action="store", help="The target host")
    parse.add_argument("start", action="store", help="The start port")
    parse.add_argument("end", action="store", help="The end port")
    args = parse.parse_args()

    target_ip = socket.gethostbyname(args.host)
    start_port = int(args.start)
    end_port = int(args.end)

    scanport()