Home Did you know ? A Novice User’s Guide to Creating a Port Scanner in Python

A Novice User’s Guide to Creating a Port Scanner in Python

by Unallocated Author

Let’s go over some basics to start off – a port is a place where information is transferred in and out of a computer. A port scanner is a software application intended to analyze a server or host for open ports.

Most commonly, port scanners are used by IT professionals in order to validate the security policies of their networks. Of course, they are also used by black hat hackers in order to isolate running services on a host.

A large variety of scanning protocols exist (for example):

  • TCP Scanning
  • SYN Scanning
  • UDP Scanning
  • ACK Scanning
  • Window Scanning
  • FIN Scanning
  • X-mas/Null Scanning
  • Protocol Scanning
  • Proxy Scanning
  • Idle Scanning
  • Cat Scanning
  • ICMP Scanning

In this article, we’re going to go over the basics of basics – a very simple Python port scanner.

(Courtesy of Doyler.net)

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

The script is easy enough to understand. You import the socket library; permitting the rest of the code to establish connections. After setting up the hosts/ports for scanning, you can set up the loops.

The script will execute the scan on each host, in sequence; looping through the port list. You can organize the exception handling for potential errors with socket connections. Finally, you’re free to set up your actual socket, the timeout, and ultimately the connection to your 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.”

You may also like