Python For Ethical Hacking

Total nerd
7 min readJan 31, 2021

Python is a very easy and powerful general purpose high level programming language with endless domains and a huge community and it’s a major player when it comes to cybersecurity and penetration testing for variety of reasons i am gonna mention

Why Python ?

The language has some major key differences that makes it very much favorable to hacking / cybersecurity enthusiasts and professionals and some of those are *

  1. Easy and readable language : unlike other languages out there such as Java and C++, Python has a very friendly syntax and very close semantics to general English language which makes it easier to both read and write Python scripts
  2. It is a powerful scripting language : Python is heavily used for cybersecurity professionals and ethical hackers to automate tasks since it’s a very good choice for writing small scripts to automate certain repetitive tasks they often do such as network scans, password cracking and other
  3. Huge set of built in libraries : There are tons of built in modules that come baked within Python for nearly any domain you could think of, ranging from scripting network tools to AI and machine learning to GUI and many many others, but what really stands out is a group of awesome modules that make writing scripts that are concerned with networking and certain aspects of ethical hacking a breeze, such as hashlib for hash functions and encrypting and socket for interacting with web sockets
  4. Massive community support : Python has been around for almost three decades now, yes 30 years! and has gathered an insanely wide audience from different age groups and work backgrounds so almost any problem you face during coding, someone else before you ran into it and got the help so you won’t run into the same issue again
  5. Open source : Being open source means developers from all around the world can always contribute to the language and suggest more features and help report and fix bugs found in it as well as creating packages for anything you can possibly imagine making the language a perfect choice for anything you desire

What Are We Coding For This Tutorial ?

To demonstrate the power of Python and see it in action we are going to write a simple script that can scan ports in a network and let us know which ones are open so we could do more research on how to exploit them, and the second script will be a password cracker also known as a dictionary attack so i hope those will get you excited enough to continue reading

Scanning For Open Ports

Before we get to the coding part let’s briefly discuss how is this gonna work, so basically we’re going to use a python module named socket which is built in to send a ping to a specified host on a range of ports and see which one returns us a response, but be careful here, don’t ever perform a port scanning against any website or IP address without explicit, written permission from the owner of the server or computer that you are targeting

Now we’re ready to write our first script to scan for open ports within a network so open up your preferred text editor / IDE which in my case is vscode but that’s totally up to you and paste in this code

from socket import *
target = input("Enter the host you want to scan: ")
addr = gethostbyname(target)
for i in range(50,500):
s = socket(AF_INET,SOCK_STREAM)
conn = s.connect_ex((addr,i))
if conn == 0:
print(f"An open port: {i}")
s.close()
print("Scan completed")

Now go to the command line (cmd) on Windows and Terminal on Mac OS or Linux and execute the command python YOUR_SCRIPT_NAME.py and hit Enter to run your program

It’ll go over ports ranging from port 50 until port 500 and it’ll take some time

Down below are the ports groups available

  1. System or well-known ports: from 0 to 1023

2. User or registered ports: from 1024 to 49151

3. Dynamic or private ports: all > 49151

Password Cracking With Python

A very common task in a penetration tester / ethical hacker work is to crack passwords, passwords are always hashed before being inserted into the website database for security reasons

What are hashes ?

A hash basically is a string of characters and numbers generated in accordance to an algorithm and there are many available hashing algorithms used in cybersecurity now and one of the most common of them now is shae256 and it is the algorithm we are going to crack in this script

The Workflow To Crack A Password

So in this scenario, you are a penetration tester breaking into a computer system and obtained some password from a database but the one you have is the hash to the password and not the plaintext password so in this case you will need to retrieve the original password from this hash or to decrypt it and this is the algorithm to do so

  1. First we give our script the hash we obtained
  2. Specify the location to our wordlist text file
  3. Hash every word in the text file
  4. Compare the hash we have with the hash obtained in step 3
  5. If those two match, it means this word we hashed is the plaintext password for the hash we have since step 1
  6. If it’s not, the program will continue until it runs out of words in the text file

Now that we understood how this process works let’s implement this above algorithm using python

import hashlib #a built in module containing many encryption algorithms
my_hash = input("Enter the hash you want to crack: ")
words = input("Words list file location: ")
for word in words:
new_hash = hashlib.shae256(word.strip().encode('ascii'))
if new_hash == my_hash:
print(f"Password found: {word}")
break
print("The password was not found in this file :( ")

No run the program same as before and check for the word

CLI Tools

A very common way to use Python scripts is to turn them into simple CLI tools to make them easier to use as you will only have to supply arguments to the script and it’ll do the work for you because as a hacker, most of the time you spend is in the terminal with a little less interaction with a GUI so how do we turn those two scripts into CLI tools to seem cooler and also for quicker use? The answer is there are two ways i’m going to demonstrate and let you decide which one is better and easier

  1. Using built in module argparse

This is a module that comes with Python by default which you can find a quick tutorial for here and the official Python documentation for it is here and it’s my personal least favorite to be honest but let’s have a look at how can we implement our port scanner using this module

import argparsefrom socket import *parser = argparse.ArgumentParser()parser.add_argument("host",help="The host you want to scan")parser.add_argument("min",help="Number of the starting port to scan",type=int)parser.add_argument("max",help="Number of the final port to scan",type=int)args = parser.parse_args()def scan(host,min,max):  addr = gethostbyname(args.host)  print(f"Scanning host : {addr}")  for x in range(min,max):    s = socket(AF_INET,SOCK_STREAM)    if s.connect_ex((addr,x)) == 0:      print(f"{x}: Open")   s.close()  print("Scan complete")scan(args.host,args.min,args.max)

In the code above we imported our required modules argparse and socket and then we created a variable representing an ArgumentParser object so we can supply it with our desired parameters

Once we call the parse_args() on the ArgumentParser() object, we have an access to those arguments through the dot notation syntax this way args.host , args.min , args.max then we proceed to pass those to our scan() function

gethostbyname() helps you convert a hostname into an ip address so we can connect to that address using the socket object

connect_ex object takes a tuple as an argument to connect and returns a flag if the connection fails or succeeds, returning 0 in case of a successful connection and 1 in case of failed connection unlike socket.connect() which raises an exception so it won’t be very neat to use it

2. Using Click

The other method which i personally prefer over argparse is using a Python module named click and down below we’re going to find out how can we transform our password cracker into a CLI tool we can use with passing arguments using the module

To get it we need to uses pip to install it using the command pip install click or pip3 install click depending on your OS

Password Cracker CLI Tool Using Click

import clickfrom socket import *@click.command()@click.option("-host",prompt="Enter the host you want to scan: ",help="Name of the host to be scanned")@click.option("-min",prompt="From port: ",help="The start of the range of ports you want to scan", default = 0)@click.option("-max",prompt="To port: ",help="The ending of the range of ports you want to scan ", default = 65000)def scan(host,min,max):  click.echo(f"Scanning host: {gethostbyname(host)}")  for x in range(min,max):    s = socket(AF_INET,SOCK_STREAM)    if s.connect_ex((gethostbyname(host),x)) == 0:      click.echo(f"{x}: open")  s.close()  click.echo("Scan complete")if __name__ == "__main__":  scan()

As you can see, using Click is far simpler than using argparse and more straightforward but it’s just a personal preference

The library provides a lot of other common CLI functionalities like passing arguments or generating a neatly formatted help page to show how to use your tool and you can check out the documentation for the library here

To run your program written in Click, just run the command in the cmd or terminal python YOUR_SCRIPT.py WITHOUT PASSING ANY ARGUMENTS

Conclusion

Python is the perfect choice to both starting to learn to program and also ethical hacking as you’ll learn a lot along the way when taking the hacking path and once you’re more advanced in programming you’ll find yourself able to script your own tools and implement many exploits and attacks easily and like i said, the language has an amazing massive community and tons of packages to choose from to help you with your hacking or programming journey

--

--