Python is a useful programming language that can be used to automate tasks in cybersecurity. In this project I created a simple port scanner to check for open ports. Ports are a point in a network where connections begin and stop. They have a number assigned to them and are associated with a protocol that uses a specific service. Hackers can exploit certain ports that should not be open to gain access to a network device.

The first step is to import the socket library to be able to utilize networking.

In the next line, ‘s’ will be the variable and ‘socket.socket’ is the class. The ‘(socket.AF_INET’ specifies that I’ll be working with IPv4. The last part specifies that the connection will be TCP.

Then I needed a host to use for the scan, so for this example I used the IP address from hackthissite.org. I ran the ping command in my terminal to grab that.

I went ahead and typed that IP address into the next line and listed a port number to test out, which can be switched out for different scans. In this case I typed in 443 for HTTPS since I know that port is open.

After that I created a function which is what will be responsible for actually conducting the port scanning function. ‘portScanner’ is the name of the function and ‘(port)’ is the variable I’ll be using for the value of the port number. Below that I inserted an if else condition so that if a scanned port is returned as closed, it prints that message, otherwise it prints it is open.

For the last line I retyped ‘portScanner(port)’, right clicked on it and selected ‘Run python file in terminal’ to run the output and see the result of the scan. This is the entire code:

This is the result of the port scan, which shows that port 443 is open. In the port number line, other port numbers can be typed in and the scan can be rerun to check for the status of it.

To test for a closed port, I changed the port number to ’21’ to see if the FTP port was open or closed.

Related Post