单线程版

速度较慢

# coding: utf-8
import socket
from datetime import datetime

# Set time-out to get the scanning fast
socket.setdefaulttimeout(0.5)

# Ask for input
remote_server = input("Enter a remote host to scan:")
remote_server_ip = socket.gethostbyname(remote_server)

# Print a nice banner with info on which host we are about to scan
print ('-' * 60)
print ('Please wait, scanning remote host ', remote_server_ip)
print ('-' * 60)

# Check what time the scan started
t1 = datetime.now()

# Using the range function to specify ports(1 - 1024)
# We also put in some error handling for catching errors
try:
    for port in range(1,1025):
        sock = socket.socket(2,1) # 2:socket.AF_INET 1:socket.SOCK_STREAM
        res = sock.connect_ex((remote_server_ip,port))
        if res == 0:
            print ('Port {}: OPEN'.format(port))
        sock.close()

except socket.gaierror:
    print ('Hostname could not be resolved.Exiting')

except socket.error:
    print ("Could't connect to the server")

# Check the time now
t2 = datetime.now()

# Calculates the difference of time
total = t2 - t1

# Print the info to screen
print ('Scanning Completed in: ', total)

多线程版

# coding: utf-8
'''  多线程 Socket TCP 端口扫描器  by: EvilCLAY'''
import socket
from datetime import datetime
from multiprocessing.dummy import Pool as ThreadPool
 
remote_server = input("Enter a remote host to scan:")
remote_server_ip = socket.gethostbyname(remote_server)
ports = []
 
print ('-' * 60)
print ('Please wait, scanning remote host ', remote_server_ip)
print ('-' * 60)
 
socket.setdefaulttimeout(0.5)
 
def scan_port(port):
    try:
        s = socket.socket(2,1)
        res = s.connect_ex((remote_server_ip,port))
        if res == 0: # 如果端口开启 发送 hello 获取banner
            print ('Port Open:{}'.format(port))
        s.close()
    except Exception as e:
        print (e.message)
 
for i in range(1,1025):
    ports.append(i)
 
# Check what time the scan started
datetimenow = datetime.now()
 
 
pool = ThreadPool(processes = 8)
results = pool.map(scan_port,ports)
pool.close()
pool.join()
 
print ('Multiprocess Scanning Completed in  ', datetime.now() - datetimenow)
Last modification:February 28th, 2021 at 03:37 pm
硬币投入口