A simple Python port scanner

This week I will share a basic Python port scanner, so that I can at least have it in my toolbox/build on it later.

Using the socket library in Python, it is fairly easy to whip up a simple port scanner, as you can see below.

import socket

hosts = ["192.168.1.1", "192.168.2.1", "192.168.2.2", "192.168.2.10"]
ports = [22, 23, 80, 443, 445, 3389]

for host in hosts:
    for port in ports:
        try:
            print "[+] Connecting to " + host + ":" + str(port)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(5)
            result = s.connect_ex((host, port))
            if result == 0:
                print "  [*] Port " + str(port) + " open!"
            s.close()
        except:
            pass

As this is a short enough script, I'll go over it piece by piece so that hopefully everyone will understand what it does.

import socket

This bit of the script just imports the socket library, which allows the rest of the code to actually make the connections.

hosts = ["192.168.1.1", "192.168.2.1", "192.168.2.2", "192.168.2.10"]
ports = [22, 23, 80, 443, 445, 3389]

These two lines setup the lists for the hosts we will scan, as well as the ports that we will check for each host. If we wanted to scan more ports or hosts, then we could add those values to these lists (or create them via a range).

for host in hosts:
    for port in ports:
        try:

The first two lines of this section set up our loops. The application will first perform the scan on each host in the list one by one. For each host, the application will loop through the port list, before continuing on to the next host. The third line just sets up our code for exception handling, for when we run into any errors with our socket connections.

            print "[+] Connecting to " + host + ":" + str(port)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(5)

Up next we display what host and port we are attempting to connect to. After that, we set up our actual socket that we will use to make the connections. AF_INET refers to the Address Family, which just means addresses from the internet (IP addresses). SOCK_STREAM is used to create a TCP connection to the host:port in question (as opposed to a datagram/UDP connection). Additionally, once we create this socket, we can set the timeout (5 seconds in this example) to speed up the scanning a bit.

            result = s.connect_ex((host, port))
            if result == 0:
                print "  [*] Port " + str(port) + " open!"
            s.close()

With our newly created socket, we then call connect_ex() to connect to our previously specified host and port. The script then attempts to connect to the host, and returns a numeric value as the response. If the result from the connection was a 0 value, then it means the connection was successful, and the script prints out that the port is open. Any other value indicates an error of some sort (generally the port being closed), and could be handled on a case by case basis. Once we have our result, we can close the socket. This prevents any connection issues or socket reuse errors in future connections.

        except:
            pass

The last two lines are to catch any exceptions from our initial "try" before we started making socket connections. That said, if any exceptions actually occur, then the application ignores them and execution continues. This is far from best practice (exceptions should at the very least be output in general), but is fine for this simple script. Some of the next steps for this program would be to handle specific exceptions properly and provide the user with more information though.

And, once this is all completed and executed, we get our output!

Python Port Scanner - Execution

The code and updates can be found in my GitHub repository.

doyler on Githubdoyler on Twitter
doyler
Ray Doyle is an avid pentester/security enthusiast/beer connoisseur who has worked in IT for almost 16 years now. From building machines and the software on them, to breaking into them and tearing it all down; he's done it all. To show for it, he has obtained an OSCE, OSCP, eCPPT, GXPN, eWPT, eWPTX, SLAE, eMAPT, Security+, ICAgile CP, ITIL v3 Foundation, and even a sabermetrics certification!

He currently serves as a Principal Penetration Testing Consultant for Secureworks. His previous position was a Senior Penetration Tester for a major financial institution.

When he's not figuring out what cert to get next or side project to work on, he enjoys playing video games, traveling, and watching sports.

2 Comments

Filed under Security Not Included

2 Responses to A simple Python port scanner

  1. Lena Furke

    Hello

    Thanks for your Python Portscanner.

    I am looking for a port scanner that scans an IP range (e.g. 192.168.0.0 – 192.168.50.255) and exports the IP used separately to different lists after open ports.

    Such as.

    Port 22 = (192.168.3.15, …)

    Port 443 = (192.168.6.72, …)

    How does the code need to be adjusted?

    Thank you for your efforts

    Lena

    • Hi Lena,

      In that case, the best bet would be to use a dictionary for the host/ports. I’d probably use IP as a key, but you could also use port as the key if you wanted to!

      Ray

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.