A port scanner is a program that sends a request to a batch of ports to check whether a port is opened. here we use an instance to explore how to write a high-performance port scanner in parallel in Python.
About Port Scanners
Port scanning is a tool used to detect open ports on servers or hosts. It is often used by computer administrators to confirm security policies, while being used by attackers to identify operational network services on the target host.
Port scan defines the port that the client sends to a certain range of server ports to confirm the port that can be used. Although it is not a malicious network activity, it is also an important means for network attackers to detect target host services and take advantage of known vulnerabilities of this service. The main purpose of port scanning is to confirm the availability of a service on a remote machine.
Scan multiple hosts to obtain a specific port called Portsweep to obtain a specific service. For example, the SQL service-based computer worm cleans the same port of a large number of hosts to establish a TCP connection on port 1433.
Python implementation
The port scanner works very easily. it is nothing more than operating the socket. if you can connect, it is determined that the port is open.
import socket def scan(port): s = socket.socket() if s.connect_ex(('localhost', port)) == 0: print port, 'open' s.close() if __name__ == '__main__': map(scan,range(1,65536))
This is the simplest port scanner.
Wait a minute. I didn't respond because the socket is blocked. it takes a long time for each connection to time out.
The timeout value we added to it.
s.settimeout(0.1)
It seems much faster to run it again.
Multi-threaded version
import socket import threading def scan(port): s = socket.socket() s.settimeout(0.1) if s.connect_ex(('localhost', port)) == 0: print port, 'open' s.close() if __name__ == '__main__': threads = [threading.Thread(target=scan, args=(i,)) for i in xrange(1,65536)] map(lambda x:x.start(),threads)
Run it. wow, it's so fast. it's almost time to throw an error. Thread. error: can't start new thread.
Think about it. this process has 65535 threads enabled. There are two possibilities: exceeding the maximum number of threads and exceeding the maximum number of socket handles. In linux, you can use ulimit to modify the settings.
If you do not modify the maximum limit, how can I use multiple threads without an error?
Add a queue to the producer-consumer mode and open a fixed thread.
Multi-thread + queue version
import socket import threading from Queue import Queue def scan(port): s = socket.socket() s.settimeout(0.1) if s.connect_ex(('localhost', port)) == 0: print port, 'open' s.close() def worker(): while not q.empty(): port = q.get() try: scan(port) finally: q.task_done() if __name__ == '__main__': q = Queue() map(q.put,xrange(1,65535)) threads = [threading.Thread(target=worker) for i in xrange(500)] map(lambda x:x.start(),threads) q.join()
Here, we open 500 threads and constantly pull tasks from the queue.
Multiprocessing + queue version
Cannot open 65535 processes at all? Or the producer-consumer model
import multiprocessing def scan(port): s = socket.socket() s.settimeout(0.1) if s.connect_ex(('localhost', port)) == 0: print port, 'open' s.close() def worker(q): while not q.empty(): port = q.get() try: scan(port) finally: q.task_done() if __name__ == '__main__': q = multiprocessing.JoinableQueue() map(q.put,xrange(1,65535)) jobs = [multiprocessing.Process(target=worker, args=(q,)) for i in xrange(100)] map(lambda x:x.start(),jobs)
Note that the queue is passed into the worker as a parameter here, because it is a process safe queue, or an error will be reported.
JoinableQueue () is also used. as the name suggests, JoinableQueue () can be joined.
Spawn Version of gevent
from gevent import monkey; monkey.patch_all(); import gevent import socket ... if __name__ == '__main__': threads = [gevent.spawn(scan, i) for i in xrange(1,65536)] gevent.joinall(threads)
Note that the monkey patch must be imported before the patch. otherwise, Exception KeyError occurs. for example, you cannot import threading first, and then monkey patch.
Gevent Pool version
from gevent import monkey; monkey.patch_all(); import socket from gevent.pool import Pool ... if __name__ == '__main__': pool = Pool(500) pool.map(scan,xrange(1,65536)) pool.join()
Concurrent. futures version
import socket from Queue import Queue from concurrent.futures import ThreadPoolExecutor ... if __name__ == '__main__': q = Queue() map(q.put,xrange(1,65536)) with ThreadPoolExecutor(max_workers=500) as executor: for i in range(500): executor.submit(worker,q)