python端口扫描(扫描0到1023端口)

来源:互联网 发布:licecap mac下载 编辑:程序博客网 时间:2024/06/11 02:06

这学期选修了“信息安全”专业的《网络安全》课程,这是网络安全课程的第一个实验,要求写一个程序,多线程扫描目的主机的端口。

很简单的一个小程序,鉴于正在学python,所以就用python写了,刚学python,所以可能有点不pythonic.

#!/usr/bin/env python# Time-stamp: <2013-06-04 10:35:58 Tuesday by pein># Email: <pein0119@gmail.com># -*- coding: utf-8 -*-import threadingimport socketdef scan(ip, port):    """    """    global portList   #建立了一个list,将目的主机开放的端口号加入portlist中(使用append函数)    try:        sk = socket.socket()        sk.settimeout(0.1)#设定连接时的超时限制,这里是100ms        address = (ip, port)        if sk.connect_ex(address) == 0:            print port            portList.append(port)    except Exception, e:        print "error %s" %e   #如果出错,打印错误信息            sk.close()class sniff(threading.Thread):    """    """        def __init__(self, ip):        """        """        threading.Thread.__init__(self)        self.ip = ip    def run(self): #重写run函数        """        """        global portBegin, portEnd, mutex        while True:            mutex.acquire()   #使用锁来实现线程同步            portBegin += 1            if portBegin > portEnd:                mutex.release()                break            mutex.release()            scan(self.ip, portBegin)def main():  #主函数    """    """    url = str(raw_input("please input a host name or a ip address\n--->"))    ip = str(socket.gethostbyname(url))    threads = []           #创建list,存储线程    global mutex, portBegin, portEnd, portList    portList = []    portBegin = 0          #设置起始的扫描端口    portEnd = 1023         #设置终止的扫描端口    mutex = threading.Lock()    for i in range(10):    #开了十个线程        thread = sniff(ip)        thread.start()        threads.append(thread)    for thread in threads:        thread.join()       #等段子线程退出    portList.sort()    print "on host \"",url,"\" port:[",    for port in portList:        print port,    print "]is open"main()            
主要思想就是建立socket,然后使用threading模块开了十个线程,并行扫描目的主机的0~1023号端口。

并使用了锁机制来实现线程同步。

输入的时候可以直接域名,也可以直接输入ip地址。

使用本机ip测试:


使用本地域名测试

启动本机的http服务,即开启本机的80端口:

可以看到端口80已经被扫描到了,证明程序有效。

(程序中的中文注释在运行时要删掉,否则会提示有不能识别的编码)

原创粉丝点击