Blog

用python写端口扫描工具(一)

总想捣鼓些什么出来,觉得写个端口扫描工具。

第一步先把源码敲出来。。。写了个扫描beta1.0,后期再修改修改。

直接上源码没毛病。

Github上也有咯      GitHub

#-*- coding: utf-8 -*-
import socket, time, thread
socket.setdefaulttimeout(3)

def socket_port(ip, port):
    """
    输入IP和端口号,扫描判断端口是否开放
    """
    try:
        if port >= 5000:
            print u'端口扫描结束'
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = s.connect_ex((ip, port))
        if result == 0:
            lock.acquire()
            print ip, u':', port, u'端口开放'
            lock.release()
        s.close()
    except:
        print u'端口扫描异常'

def ip_scan(ip):
    """
    输入IP,扫描IP的0-X端口情况
    """
    try:
        print u'开始扫描 %s' % ip
        start_time = time.time()
        for i in range(0, 5000):
            thread.start_new_thread(socket_port, (ip, int(i)))
        print u'扫描端口完成,总共用时 :%.2f' %(time.time() - start_time)
        raw_input("Press Enter to Exit\n")
    except:
        print u'扫描ip出错'


if __name__=='__main__':
    url = raw_input('Input the ip you want to scan:\n')
    lock = thread.allocate_lock()
    ip_scan(url)

没有评论

Leave a Reply

你必须登入才能评论。