HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python Port Scanner 2.0

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scannerpythonport

Problem

A few months ago I put up a port scanner for review. Now, I've updated it with some new Python knowledge and integraing the feedback I got.

Some things I specifically think might be wrong with it or feel clunky to me:

  • Default argument values for the scan_ports function. I set the default values, but then I have to check for None again when I enter the block. I was actually kind of surprised and disappointed that, if the arg was None, it didn't just automatically take the default. Any better way to handle this?



  • The is_address_valid function. I'm not entirely sure I did this the proper way, with catching multiple exception types. Not sure if I'm catching things I shouldn't be, or if there's a more elegant way to approach it.



  • Detecting the operating system. Not sure if the standard is to use os.name or platform.system().



  • When is it acceptable to actually add line-breaks into your function bodies? Most of the scripts I've seen are really, really loathe to do so, and I kind of get it since everything in Python is space-based instead of bracket-based. But sometimes the function bodies seem to be a bit too long and it starts to look bad.



  • (More of a StackOverflow question, but still, if someone wants to throw it in as a tidbit...) Why do the arguments in socket.socket().connect((host, 80)) have to be wrapped in another set of parentheses? Found that this was the way to do it, but couldn't find in the API why it has to be that way.



Any tips or feedback are greatly appreciated!

Also, I think @GarethRees was skeptical in the other question that I might be using this for malicious purposes. I'm actually just learning from a book called Violent Python, and a port scanner is the first thing it goes over in the book. The book is a bit more interesting than a normal textbook that goes over different variations of "Hello World!", haha.

```
#!/usr/bin/env python3

import argparse
import errno
import functools
import multiprocessing
import

Solution

You're opening a lot of sockets but not closing them. Those are likely file descriptor leaks. (Whether or not it actually leaks depends on the garbage collector's behaviour.)

If you're using concurrent.futures.ThreadPoolExecutor for the multithreaded version, then you should also use concurrent.futures.ProcessPoolExecutor for the multiprocess version.

ping usually implies an ICMP echo. If you're actually doing a TCP scan, call it tcp_ping or something.

The status messages are misleading. "Windows OS detected" sounds like you performed OS fingerprinting on the remote peer, but you actually mean that the port scanner is running on a Windows host.

Context

StackExchange Code Review Q#46842, answer score: 4

Revisions (0)

No revisions yet.