I have written a rather simple port scanner using Python, and I would like to know things I could do better regarding:
Code quality, making the code in general better
Performance, making the code run faster and more efficient
Making the scan more lightweight for the system being scanned so there is no risk of it crashing
At the moment it takes around 160 seconds to scan all ports.
import socket
import time
import threading
from queue import Queue
socket.setdefaulttimeout(0.25)
print_lock = threading.Lock()
target = '127.0.0.1'
def portscan(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
con = s.connect((target, port))
with print_lock:
print('Port', port, 'is open!')
con.close()
except:
pass
def threader():
while True:
worker = q.get()
portscan(worker)
q.task_done()
q = Queue()
startTime = time.time()
for x in range(100):
t = threading.Thread(target=threader)
t.daemon = True
t.start()
for worker in range(1, 65536):
q.put(worker)
q.join()
print('Time taken:', time.time() - startTime)
-
1\$\begingroup\$ just putting it out there stackoverflow.com/a/16780297/1190388 \$\endgroup\$hjpotter92– hjpotter922017年12月19日 19:25:14 +00:00Commented Dec 19, 2017 at 19:25
1 Answer 1
The review only addresses this aspect:
Code quality, making the code in general better
Naming
The PEP 8 style guide recommends snake_case for function and variable names.
Function portscan
would be better as port_scan
.
Variable startTime
as start_time
.
It also recommends all upper case letters for constants:
TARGET = '127.0.0.1'
Use underscore characters to make large numeric literals easier to read and understand. For example, change:
65536
to:
65_536
Documentation
The PEP-8 style guide recommends adding docstrings for functions. For example:
def portscan(port):
""" Scan a port """
The docstring should also describe what the input is and what the function does.
Simpler
Since the x
variable is not used inside this for
loop:
for x in range(100):
the _
placeholder can be used:
for _ in range(100):
f-string
The following line:
print('Time taken:', time.time() - startTime)
can be improved using an f-string with a precision specifier to limit the number of places after the decimal:
print(f'Time taken: {time.time() - startTime:.2f} seconds')
The message is also clearer with the addition of time units ("seconds").