Basic Vulnerablity Scanning in Python

Introducing myself to good cyber security practices

I haven't really worked on any cyber security related projects before, and now that I am back home because of the Palisades fire, I decided now's a better time than ever to get started on a project. Today I decided to work on a port vulnerability scanner for my computer using Python's socket libarary.

First, I started by creating a virutal environment to ensure no conflicts were happening within my libraries:

python -m venv .venv

One of the first issues I encountered was:

(.venv) ./main.py
zsh: permission denied: ./main.py

This was caused by a permissions error in my file, so I checked the permissions and then edited them to allow all groups to execute the program by running:

ls -l main.py
chmod +x main.py

Another small python issue I noticed was that because I was coding and running my code using VSC, I did not need to specify a shebang, but rather ensure that I was running my code properly through chosing the virtual environment as my interpreter.

Code Portion

My code first asks the user to input their IP address (I found mine through running the command 'ifconfig' and looking for en0).

Then it runs through the first 20 ports, scanning them to check if they are open or closed.

import socket
import nmap

# scan 1000 ports

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)

# get user/host IP
host = input("[*] Enter The Host to Scan: ")

def port_scanner(port):
    if sock.connect_ex((host, port)):
        print ("[!] Port %d is closed" % (port))
    else:
        print ("Port %d is open" % (port))

for port in range(1,20):
    port_scanner(port)

This socket uses IPv4 to connect and TCP sockets, since TCP sockets are more reliable than UDP sockets. In the port scanner function, the difference of using connect_ex() instead of connect() is that my program will not raise a 'socket.timeout' if a connection is not made, but rather just return with error code 0. The benefit of this is for asynchronous connections.