Penetration testing

How to write a port scanner in Python in 5 minutes: Example and walkthrough

August 30, 2021 by Jeff Peters

What is a port scanner and how does one work? Learn how easy it is to build your own basic Python port scanner in this walkthrough from Infosec Skills author Keatron Evans. Get your own port scanner up and running in a few minutes, then play around and see what kind of functionality you can add to it.

How to write a Python port scanner

In this episode of Cyber Work Applied, Keatron helps you build your own port scanner, a tool that can be useful for a variety of different cybersecurity purposes.

Watch the full walkthrough of building your own port scanner below:

Write a port scanner in Python in 5 minutes | Free Cyber Work Applied series

New episodes of Cyber Work Applied are released every other week. Check out the full collection of free Cyber Work Applied training videos.

More Free Training Videos

Python port scanner script: Demo and walkthrough

The edited transcript of Keatron’s how to make a port scanner in Python walkthrough is provided below. It’s broken into each step Keatron covers in the video, along with the Python port scanner script for you to copy.

Creating a port scanner with Python

(0:00–0:55) Hello, I’m Keatron Evans and today you’re going to learn some basic Python with me by writing a port scanner in about five minutes. Open up your Kali terminal or any Linux terminal and let’s go.

I’m going to show you the basics of how we write a very fundamental Python script — a basic port scanner. I want you to begin by just copying the code. Follow along, and write down exactly what I’m writing in my script. Don’t worry about trying to understand what a variable is or what a module is. We will go through some of these things, but I really want you to focus on just getting the code copied verbatim.

Once you have a working port scanner, then you can challenge yourself to expand on it and go dig into some of this terminology.

Using import in Python

(0:56–1:55) What we’re doing in the beginning here is an import. We’re telling Python to go ahead and bring in this functionality. When we say import socket — somebody’s already written pieces of code that can do things like go out and connect to the internet or go out and connect to other IPs. So as a Python developer, you don’t need to write code from scratch that allows you to go out and connect to things. Somebody’s already written that in another module.

In this case, we’re importing those functions because we’re going to need that later in our script, or we’re going to need our script to be able to do those things. We’re importing socket, we’re importing sub-process and we’re importing sys.

import socket
import subprocess
import sys

Just remember: These are things that someone else coded in the Python language that allows us to automate some of the stuff that we’re going to be doing.

Using datetime in Python

(1:56–2:15) The next thing is:

from datetime import datetime

What we’re doing here is — we want to be able to know what the current date and time is. The reason for that is we’re going to have the script tell us how long it took to execute. For it to be able to do that, it’s going to need to know, here’s where I started, here’s when I ended.

How to clear your screen in Python

(2:16–2:26) Next, we want to blank the screen. If there’s anything on the screen, you want to make that go away. We’re doing that here with basically a clear-screen-type function.

#Blank your screen'clear', shell=True)

Asking for input in Python


After that, we’re going to ask for some basic input.

#Ask for input
remoteServer = raw_input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyname(remoteServer)

We’re defining remoteServer here as this particular function, and then we say, enter a remote host to scan.

The remoteServerIP is going to be the result of what you enter when it asks you to enter the remote host to scan. This could be in the form of an IP address or URL or whatever it is you happen to be wanting to scan.

Printing information in Python

(2:52–3:06) Next, we’re going to print a banner for us or give us some information about what we’re doing.

#Print a nice banner with information on which host we are about to scan
print "_" * 60
print "Please wait, scanning remote host", remoteServerIP
print "_" *60

We basically just say, please wait as we scan the remote host and then whatever the IP is we entered when we first started the scan.

Checking the date and time in Python

(3:07–3:34) Next, we’re going to check the date and time again because we need to know when the scan actually started.

#Check the date and time the scan was started
t1 =

We’re defining t1 as the current date and time. That way, at any point in our code, we can say t1 and it will actually tell us what the current date and time is without us having to type out that long function again. That’s the purpose of doing that.

Using a function to specify ports and errors in Python

(3:35–5:06) Next, we’re going to use another function here to specify ports.

#Using the range function to specify ports
#Also we will do error handling

for port in range (1,5000):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServerIP, port))
if result ==0:
print "Port {}:        Open".format(port)

except KeyboardInterrupt:
print "You pressed Ctrl+C"

except socket.gaierror:
print "Hostname could not be resolved. Exiting"

except socket.error:
print "Couldn't connect to server"

We say, for port in range. This is what we call a for loop. In other words, it’s a way to repeat something over and over again. That’s what a loop is, for the range in 1–5,000. What we’re doing here is we’re going to scan all ports between one and 5,000. So we’re going to check that on each IP address we scan.

The next part of this is using socket. Remember that earlier we said import socket. Now we’re actually using that module we imported. Basically, we say, let’s use that to connect to something. The something that we’re going to connect to is whatever IP address it is we entered when we started this. Once we get a connection, we need to tell our script what to do with that connection.

In this particular example, we’re going to say Ctrl+C if we want to end the script or stop the script from running. Or if the script is unsuccessful in connecting — maybe you gave it an IP address that’s not really there — then we need to tell the script how to respond to us. In other words, we call that error control. We can see that we’re telling it if you get a connection, go ahead and print the information about that — the IP and the ports — or if you can’t connect, tell us, I couldn’t connect to that IP or that server. That’s all we’re doing here.

Calculating time for the script to run in Python

(5:07–5:38) After the script is completed, we’re going to call our date function again.

#Checking time again
t2 =

#Calculate the difference in time to now how long the scan took
total = t2 - t1

#Printing the information on the screen
print 'Scanning Completed in in ', total

We’re defining date and time now as t2. So we’re going to call t1 and t2 and say, take t1, whatever the date and time was, then subtract that from t2, which is what the date and time is now, and that will tell us how long it took for the script to run.

We’re going to take that number and print that in a message that says, scanning completed in however many seconds. That’s the basic functionality of the script.

Using your new Python port scanner

(5:07–6:31) Now, let me show you what happens when we actually run the script and give it a target. What we see is it’s coming back and telling us specifically that this particular machine at this IP or URL has exactly these ports open.

That’s what a basic port scanner looks like in Python. If you really want to challenge yourself, what I’d like to see you do in your own time is see if you can figure out how to make the script not only tell us the open ports, but tell us what’s actually running in those ports.

More free training videos

For more free videos, check out Infosec’s Cyber Work series. Each week on our Cyber Work Podcast, we sit down with a new cybersecurity practitioner to discuss their career journey and tips to break in or move up in the industry. On Cyber Work Applied, Infosec instructors like Keatron provide walkthroughs to help build your skills and put them into action, including:

  • Common attacks like man-in-the-middle, cross-site scripting and watering holes
  • Breakdowns of real-world incidents, such as DDoS attacks and data breaches
  • How to use popular tools to crack passwords, perform reconnaissance and protect networks
  • Security basics like cryptography, phishing and cloud computing
  • And many more!

More Free Training Videos

Posted: August 30, 2021
Articles Author
Jeff Peters
View Profile

Jeff Peters is a communications professional with eight years of experience creating cybersecurity-related content. As the Director of Content Marketing at Infosec, he focuses on developing materials to help cybersecurity professionals improve their skills and advance their careers. He oversees the Infosec Resources website, the Cyber Work series (Cyber Work Podcast, Cyber Work Applied and Cyber Work Live) and a variety of other Infosec content.

Leave a Reply

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