Introduction to Coding
There are many debates online about whether or not you need to know coding to get into cybersecurity. In most cases, you don’t, but if you want to stand out from the crowd and get some of the best cybersecurity positions, you will need to learn to code. Cybersecurity practitioners use coding to build tools and automate tasks so they can be more efficient and effective in their positions. Most of the interviews at top tech companies for cybersecurity positions will involve a coding challenge.
Languages
There are many different programming languages, and choosing a first programming language can seem like a difficult task. Based on our team’s experience, Golang and Python are the most common languages for cybersecurity practitioners. This introduction will focus on Python.
In the field of cybersecurity, Python continues to be a dominant language because of its simplicity, readability, and efficiency. Its straightforward syntax and powerful libraries make it a great tool. This page lays the foundations of coding in Python, guiding you from the initial setup to the basics of fundamental concepts in programming.
Installing python
Before installing Python, it’s important to choose the correct version. Python 3.x is the current and actively developed version, featuring improvements and enhancements over Python 2.x, which has reached the end of its life. For cybersecurity tasks, Python 3.x is recommended due to its modern features and support.
Installing Python on Windows
- Download Python: Visit the downloads section of the official Python website. The website should automatically suggest the best version for Windows. Click the download button for the latest Python 3.x version.
- Run the Installer: Once the download is complete, run the installer. Ensure you check the box that says “Add Python 3.x to PATH” before clicking “Install Now.” This step makes Python accessible from the Command Prompt.
- Verify Installation: Open the Command Prompt and type
python --version
and press Enter. If Python is successfully installed, you should see the version number displayed.
Installing Python on macOS
- Download Python: Go to the downloads section of the official Python website and download the latest Python 3.x version for macOS.
- Run the Installer: Open the downloaded package and follow the instructions to install Python. macOS might prompt you to verify the installation since it was downloaded from the internet.
- Verify Installation: Open the Terminal and type
python3 --version
to check if Python is installed correctly. macOS usespython3
command to distinguish from Python 2.x, which might already be installed on your system.
Installing Python on Linux
Most Linux distributions come with Python pre-installed. However, it might not be the latest version. To install or update Python on Linux:
- Open the Terminal: Use the terminal to install Python.
- Install Python: For Debian-based distributions (like Ubuntu), use
sudo apt-get update
followed bysudo apt-get install python3
. For Red Hat-based distributions, usesudo yum install python3
. - Verify Installation: Type
python3 --version
in the terminal to confirm the installation.
Programming Fundamentals with Python
This section will guide you through the core programming fundamentals using Python, laying the groundwork for your future cybersecurity endeavors.
Variables
Think of variables as containers that store values. In Python, creating a variable is as simple as assigning a value to it. Python is dynamically typed, which means you don’t need to declare the type of variable upfront.
message = "Hello, Cyber World!"
counter = 100
Data Types
The primary types in Python include integers (int
), floating-point numbers (float
), strings (str
), and booleans (bool
). Python automatically recognizes the type of data a variable holds.
Numeric values
- Integers (int): Integers in Python are used to represent whole numbers, both positive and negative. Unlike some programming languages, Python 3 integers have no fixed size limit (except for memory constraints).
positive_integer = 123
negative_integer = -456
- Floating point numbers (float): Floating-point numbers, or floats, represent real numbers and can contain a decimal point. They are specified in Python with a dot (.) or using scientific notation. Due to the way computers represent floating-point numbers, some floats might not have exact representations in binary, leading to precision issues. For most applications, this is not a concern, but it can become significant in financial calculations or when exact decimal representation is required.
simple_float = 3.14
scientific_notation = 1.5e2 # 1.5 * 10^2 = 150.0
# Precision example
precision_test = 0.1 + 0.2 # May not exactly equal 0.3
Strings
Strings are used to store and represent text data. They are sequences of Unicode characters, which enables python to support various types of texts, including emojis and characters from different languages. Strings in Python are immutable, meaning once a string is created, its content cannot be changed, although you can create new strings from existing ones through manipulation. Strings can be on a single line or span across multiple lines.
single_quoted_string = 'Hello, Python!'
double_quoted_string = "Hello, Python!"
multi_line_string = """This is
a multi-line
string."""
Lists
Lists are versatile containers used to store an ordered sequence of elements. They can hold items of different types, including integers, strings, floats, and even other lists. Unlike strings, lists are mutable, meaning their content can be modified after creation. This flexibility makes lists fundamental for data manipulation, iteration, and complex data organization in Python programming.
# Creating a list with mixed element types
mixed_list = [42, "hello", 3.14, [1, 2, 3]]
# Accessing the first element
first_element = mixed_list[0] # first_element will have a value of 42
# Accessing a nested list element
nested_element = mixed_list[3][1] # nested_element will have a value of 2
Tuples
Tuples serve as immutable sequences, meaning once a tuple is created, its contents cannot be altered. This characteristic makes tuples ideal for storing a collection of items that should not change throughout the execution of a program. Tuples are ordered, allowing you to access elements by their index, and they can hold mixed data types, similar to lists. However, their immutability grants them unique advantages in terms of performance and safety in concurrent environments.
# Creating a simple tuple
simple_tuple = (1, "two", 3.0)
# A single-element tuple needs a trailing comma
single_element_tuple = (42,)
# Parentheses are optional
optional_parentheses = "hello", "world"
# Accessing elements
first_element = simple_tuple[0] # 1
second_element = simple_tuple[1] # "two"
# Appending an element to the end
mixed_list.append("new item")
# Inserting at a specific position
mixed_list.insert(1, "inserted item")
# Removing by value
mixed_list.remove("hello")
# Removing by index and getting the removed item
removed_item = mixed_list.pop(1) # "inserted item"
Dictionary (dict)
Dictionaries are dynamic, unordered collections that store mappings of unique keys to values. They are mutable, allowing you to add, remove, or modify elements after creation. Keys in a dictionary must be immutable types (such as strings, numbers, or tuples that contain only immutable elements) and are used to retrieve the corresponding values.
# Creating a simple dictionary
user_profile = {"username": "tech_enthusiast", "password": "securePass123", "email": "[email protected]"}
# Accessing elements
username = user_profile["username"]
email = user_profile.get("email")
# Accessing a non-existing key with get to avoid KeyError
location = user_profile.get("location") # Returns None
# Adding a new key-value pair
user_profile["location"] = "Earth"
# Updating an existing value
user_profile["password"] = "evenMoreSecurePass456"
# Removing a key-value pair
del user_profile["password"]
# Removing a key-value pair with pop, returning the value
email = user_profile.pop("email")
# Iterating through key-value pairs
for key, value in user_profile.items():
print(f"{key}: {value}")
# Iterating through keys
for key in user_profile.keys():
print(key)
# Iterating through values
for value in user_profile.values():
print(value)
Sets
Sets are an invaluable data structure for storing unordered collections of unique elements. They are similar to mathematical sets, making them ideal for operations like unions, intersections, differences, and symmetric differences. Sets automatically remove duplicate elements, ensuring each element is unique within the collection.
# Creating a set with curly braces
number_set = {1, 2, 3, 3, 4} # Duplicates are removed, resulting in {1, 2, 3, 4}
# Creating a set from a list to remove duplicates
list_with_duplicates = [1, 2, 2, 3, 4]
unique_set = set(list_with_duplicates) # {1, 2, 3, 4}
# Iterating through a set
for num in number_set:
print(num)
# Adding an element
number_set.add(5)
# Removing an element (raises KeyError if not found)
number_set.remove(1)
# Discarding an element (does nothing if not found)
number_set.discard(42)
# Clearing all elements
number_set.clear()
Booleans
Booleans represent one of the simplest data types with two values: True and False. They are the backbone of conditional statements (discussed in the Control Structures section) and logic in programming, allowing you to make decisions and control the flow of execution based on certain conditions.
is_active = True
is_registered = False
# Logical AND
print(True and False) # False
# Logical OR
print(True or False) # True
# Logical NOT
print(not True) # False
Operators
Arithmetic Operators
Arithmetic operators are used for performing mathematical operations like addition, subtraction, multiplication, and division.
x = 10
y = 3
# Addition
print(x + y) # 13
# Subtraction
print(x - y) # 7
# Multiplication
print(x * y) # 30
# Division
print(x / y) # 3.333...
# Floor Division
print(x // y) # 3
# Modulus (remainder)
print(x % y) # 1
# Exponentiation
print(x ** y) # 1000
Comparison Operators
Comparison operators are used to compare two values and return a boolean value (True or False).
# Equal
print(x == y) # False
# Not equal
print(x != y) # True
# Greater than
print(x > y) # True
# Less than
print(x < y) # False
# Greater than or equal to
print(x >= y) # True
# Less than or equal to
print(x <= y) # False
Assignment Operators
Assignment operators are used to assign values to variables.
# Assignment:
x = 10
x += 5 # x = x + 5
x -= 5 # x = x - 5
x *= 5 # x = x * 5
x /= 5 # x = x / 5
x %= 5 # x = x % 5
x //= 5 # x = x // 5
x **= 5 # x = x ** 5
Control Structures
Control structures are used to specify the execution of code within a program. It can be used to determine if a block of code is executed or not, or it can be used to repeat certain code.
Conditional Statements
Python uses if
, elif
, and else
statements to execute code based on conditions. These are fundamental for decision-making in your programs.
if is_hacker:
print("Access Granted.")
else:
print("Access Denied.")
#nested if statement
if age >= 18:
if grade >= 90:
print("You are an adult with an A grade.")
else:
print("You are an adult without an A grade.")
Loops
Loops are used to repeat a block of code multiple times. Python provides for
loops and while
loops.
- For Loops: The for loop allows you to iterate over the items of any sequence (such as lists, strings, tuples, or even dictionaries) in the order they appear. This makes it an essential construct for looping through data structures, executing a block of code multiple times, and creating more dynamic and efficient programs
#iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Iterating from 0 to 4
for i in range(5):
print(i)
- While Loops: The while loop is a control flow tool that repeatedly executes a block of code as long as a given condition is True. It’s especially useful for situations where the number of iterations is not known before the loop starts, such as reading from a stream of data or polling a system state.
# print 0 to 4
count = 0
while count < 5:
print(f"Count is {count}")
count += 1 # Increment count to avoid an infinite loop
# Exiting a loop with break
n = 0
while True: # Be cautious with while True
if n == 3:
break # Exit loop when n is 3
print(n)
n += 1
# Skipping part of a loop with continue
n = 0
while n < 5:
n += 1
if n == 3:
continue # Skip the print statement for n == 3
print(n)
Functions
Functions are used to organize code into reusable blocks to avoid repetition, improve readability, and make maintenance easier.
#define a greet function
def greet():
print("Hello, World!")
#calling/running the function
greet()
#defining a function with a name argument/variable
def greet(name):
print(f"Hello, {name}!")
#calling the function
greet('Alice')
#return statements send back a value
def add(x, y):
return x + y
result = add(2, 3) # result is 5
print(result)
#setting a default parameter
def greet(name="World"):
print(f"Hello, {name}!")
greet() # Outputs: Hello, World!
greet("Dave") # Outputs: Hello, Dave!
Package Management
The import system allows you to modularize your code into separate files (modules) and directories (packages). You can also import built-in packages/libraries as well as third party packages/libraries. Understanding how to import modules and packages efficiently can streamline your development process and make your code cleaner and more maintainable.
#import the built-in math package
import math
print(math.sqrt(16))
#imports the path function from the built-in os package
from os import path
print(path.exists('/tmp'))
#import a module from a separate file
from mypackage import mymodule
Installing a Third-Party Package
The Python Package Installer, pip, allows you to install packages from the Python Package Index (PyPI), manage package versions, and handle package dependencies.
#install the requests package for web requests
pip install requests
#installing a specific version of a package
pip install requests==2.22.0
#uninstall package
pip uninstall requests
#upgrade a package
pip install --upgrade requests
#export a list of packages
pip freeze > requirements.txt
How Python is Used in Cybersecurity
Python is used by both offensive and defensive teams to be more efficient and effective in their duties. Defenders use python to automate the deployment, configuration, monitoring, and respond of their security tool. Attackers use python to automated reconnaissance, exploitation, and exfiltration of data.
Recommended Books
This was just a brief introduction to Python to get you started. If you want to learn more, below is a book that we highly recommend.
For those interested, I’ve included an affiliate link to purchase the book. Using this link not only gets you a great resource for your studies but also supports our blog at no additional cost to you:
Next Steps in Your Learning Journey
With these basics under your belt, you’re well on your way to deeper cybersecurity learning. Dive into advanced topics and start applying your knowledge in practical scenarios. Check-out our Linux foundations page.
Remember, the field of cybersecurity is vast and ever-evolving. Stay curious, keep learning, and use SecureBitsBlog as your guide through the fascinating world of digital security.