我想在Python中創建一個端口掃描器。我得到了掃描儀,但它需要四十五分鐘才能打印結果。我開始實行線程,但是我無法弄清楚如何把不同的範圍到腳本。我開始創建一個全局變量,並嘗試在每個線程中傳遞它。不幸的是,它不能正常工作,我得到一個無效的語法錯誤。以下是代碼。Python的端口掃描器與線程
import socket
import os
import sys
from threading import Thread
server = raw_input("Please enter a server name ")
def portConnect():
global num
try:
serv_ip = socket.gethostbyname(server) # connects to server through try
print "Please wait, scanning remote host", serv_ip
for port in range(num):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connect = sock.connect_ex((serv_ip, port))
if connect == 0:
print "Port {}: Open".format(port)
sock.close()
except socket.gaierror:
print """
I can't find that server, idiot! Try again
"""
sys.exit()
for i in range(1):
t = Thread(target=portConnect,(num=100))
t.start()
我在做什麼錯?
看看在多頁https://docs.python.org/2/library/multiprocessing.html,特別是在'Pool'和'Process'這可能是最合適的你的情況。 – sal