码迷,mamicode.com
首页 > 其他好文 > 详细

端口扫描器

时间:2016-05-23 14:39:34      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

从单线程到多线程版,一次迭代

# coding:utf-8
# author:jwong

import sys
from socket import *

def main(start_port, end_port, host):
    target_ip = gethostbyname(host)
    opened_ports = []
    for port in range(start_port, end_port):
        print "port scanning is %s " % port
        sock = socket(AF_INET, SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex((target_ip, port))
        if result == 0:
            opened_ports.append(port)
    print_port()


def print_port():
    print("Opened ports:")
    for i in opened_ports:
        print "%s \n" % i

if __name__ == ‘__main__‘:
    if len(sys.argv) < 3:
        print ‘useage python 192.168.1.1 1-65535‘
        exit(0)
    host = sys.argv[1]
    portstrs = sys.argv[2].split(‘-‘)

    start_port = int(portstrs[0])
    end_port = int(portstrs[1])
    main(start_port, end_port, host)

 

多线程版本1:

# coding:utf-8
# author:jwong
import threading
import Queue
from socket import *
queue = Queue.Queue()
thread_num = 20
def scan(target):
    opened_ports = []
    while not queue.empty():
        port = queue.get()
        sock = socket(AF_INET, SOCK_STREAM)
        sock.settimeout(2)
        result = sock.connect_ex((host, port))
        if result == 0:
            opened_ports.append(port)
        for i in opened_ports:
            print "%s \n" % i

host = ‘192.168.31.232‘
lists = [22, 25, 80, 8080, 81, 1433, 3306]
# 放入队列中
for list in lists:
    queue.put(list)
for i in range(thread_num):
    s = threading.Thread(target=scan, args=(host,))
    s.start()

增加了线程锁,防止阻塞

# coding:utf-8
# author:jwong

import socket
import time
import thread


def connect(ip, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((ip, host))
        if result == 0:
            lock.acquire()
            print ip ‘:‘,port,‘open‘
            lock.release()
        sock.close()
    except:
        print ‘port scan error!‘


def scan(ip):
	try:
		print ‘start scan now!‘
		start_time = time.time()
		for i range(0,65534):
			thread.start_new_thread(connect, (ip,int(i)))
			print ‘total time in scan %.2f‘ % (time.time()-start_time)
			raw_input(‘press anykey to exit!‘)


	except :
		print ‘ip scan error!!‘

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

  

  

  

端口扫描器

标签:

原文地址:http://www.cnblogs.com/jwong/p/5444110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!