Skip to content

You will put Python into practice and focus on automating cybersecurity-related tasks, which requires working with files. You’ll be introduced to opening and reading files. Then, you’ll learn to parse files and structure their contents. Finally, you’ll focus on strategies for debugging code.

Learning Objectives

  • Use Python to automate tasks performed by security professionals.
  • Use Python to open and read the contents of a file.
  • Use Python to parse a file.
  • Practice debugging code.

Python for automation


Video: Welcome to module 4

Python for Security Ninjas: Automating Your Workflow

Gear up security analysts! This module is your practical toolbox for wielding Python against cyber threats. We’ll tackle:

  • Log Wrangling: Open and interpret those massive security logs with ease, making your analysis swift and efficient.
  • File Parsing Prowess: Extract the juicy security intel you need from any file format, transforming cryptic data into actionable insights.
  • Debugging Dojo: Master the art of error slaying! Learn to decipher Python’s messages and keep your code running smoothly.

By the end, you’ll be a Python powerhouse, automating tasks and extracting intel like a seasoned security pro. Let’s dive in!

This summary captures the key points:

  • Focuses on practical application of Python for security analysts.
  • Highlights three key skills: log handling, file parsing, and debugging.
  • Uses engaging language and metaphors to convey excitement.
  • Creates anticipation for the upcoming content.

We’ve learned a lot about
Python together already, and we still have more to cover. In this section, we’re going to explore how
a security analyst like yourself puts Python
into practice. As a security analyst, you will likely work with
security logs that capture information on various
system activities. These logs are often very large and hard to
quickly interpret. But Python can easily automate these tasks and make things
much more efficient. So first, we’ll focus on opening and reading
files in Python. This includes log files. We’ll then explore
parsing files. This means you’ll be able to
work with files in ways that provide you with the
security-related information that
you’re targeting. Finally, part of writing
code is debugging code. It’s important to be
able to interpret error messages to
make your code work. We’ll cover common types of Python errors and
ways to resolve them. Overall, after completing
this section, you’ll have a better
understanding of Python and how as a security
analyst you can use it. I can’t wait to join you.

Video: Automate cybersecurity tasks with Python

Automating Security with Python: Three Powerful Examples

Ever feel overwhelmed by endless security checks? Automation is your secret weapon! Python shines in automating security tasks, and here’s how:

1. Guarding Sensitive Data: Imagine guarding patient records in a healthcare database. Python can script a timeout policy, locking out users who spend over 3 minutes logging in (suspicious password guessing?). Track login attempts, username, time, and location, flagging unusual patterns like early morning access from unauthorized locations or simultaneous logins from different IPs.

2. Thwarting Cyberattacks: Infiltrations by malicious actors targeting client information? Python helps you track and analyze user logins. Flag those logging in at odd hours, from unrecognized locations, or simultaneously from multiple IPs.

3. Monitoring Customer Apps: Protecting password-accessed customer applications? Use Python to monitor login attempts and flag suspicious activity like multiple failed logins within a short timeframe. Parse log files containing username, IP, timestamp, and login status, using conditionals to identify potential threats.

These are just a glimpse of Python’s power in security! With automation, you can focus on strategizing and leave the repetitive tasks to your Python ally.

Key takeaways:

  • Python automates tedious security tasks, freeing up analysts for proactive measures.
  • Examples showcase its application in healthcare, legal, and customer-facing scenarios.
  • The excitement is palpable – Python empowers security analysts to become solution makers!

Here’s a tutorial outline on “Automating Security with Python”:

I. Introduction

  • Greet learners and introduce the tutorial’s purpose: empowering them to automate security tasks with Python.
  • Highlight Python’s strengths for security automation: readability, extensive libraries, and versatility.
  • Outline the tutorial’s structure and learning objectives.

II. Essential Python Concepts for Security

  • Data Types: Numbers, strings, lists, dictionaries, and their roles in security data structures.
  • Variables and Operators: Storing and manipulating data for security analysis.
  • Conditional Statements: if, elif, else for decision-making based on security conditions.
  • Loops: for and while loops for iterating through security data and performing repetitive tasks.
  • Functions: Organizing code for reusable security tasks and modularity.
  • Modules: Importing external libraries to extend Python’s security capabilities.

III. Automating Common Security Tasks

  • File Handling: Opening, reading, writing, and parsing security-related files (e.g., logs, configuration files).
  • Network Security:
    • Scanning for vulnerabilities using Python libraries like Nmap.
    • Analyzing network traffic with tools like Scapy.
  • Password Management:
    • Generating strong passwords with random module.
    • Storing passwords securely using hashing techniques.
  • Incident Response:
    • Collecting and analyzing forensic data (e.g., logs, system snapshots).
    • Automating threat containment and remediation actions.

IV. Hands-on Security Projects

  • Project 1: Building a Password-Lockout Script: Implement a timeout policy to lock out users after multiple failed login attempts.
  • Project 2: Analyzing Log Files for Anomalies: Parse log files to detect suspicious patterns like unusual login times or IP addresses.
  • Project 3: Creating a Network Port Scanner: Scan for open ports on a network to identify potential vulnerabilities.

V. Advanced Topics (Optional)

  • Regular Expressions: Extracting complex patterns from security data.
  • Object-Oriented Programming: Organizing code for complex security applications.
  • Interacting with Security APIs: Integrate Python with external security tools and services.

VI. Conclusion

  • Summarize key takeaways and best practices for security automation with Python.
  • Encourage learners to continue exploring Python’s security capabilities.
  • Provide resources for further learning and practice.

Automation is a key concern
in the security profession. For example, it would
be difficult to monitor each individual
attempt to access the system. For this reason, it’s
helpful to automate the security controls
put in place to keep malicious actors
out of the system. And it’s also helpful to automate the detection of
unusual activity. Python is great for automation. Let’s explore three
specific examples of this. First, imagine you’re
a security analyst for a health care
company that stores confidential patient records
in a database server. Your company wants to implement additional controls to
protect this information. In order to enhance the
security of the records, you decide to implement a
timeout policy that locks out a user if they spent more than three minutes
logging into the database. This is because
it’s possible that if a user is spending
too much time, it could be that they are
guessing the password. To do this, you can use Python to identify when
a user has entered a username and start tracking the time until this user
enters the correct password. Now, let’s cover a
different example. This time, imagine you are a security analyst
working at a law firm. There have recently been some ongoing security
attacks where threat actors hack into employee accounts and attempt to steal client information. They then threaten to
use this maliciously. So the security team
is working to target all security
vulnerabilities that allow these attackers to break into
the company’s databases. You personally are
responsible for tracking all user logins by checking their
login timestamp, IP address, and
location of login. For example, if a user logs in during the early
hours of the morning, they should be flagged. Also, if they are
logging in from a location that’s not one of the two established
work zones, you must flag their account. Finally, if a user is simultaneously logged in from
two different IP addresses, you must flag their account. Python can help you
keep track of and analyze all of this
different login information. Let’s consider one
final example. Imagine you are a
security analyst working at a large organization. Recently, this organization has increased security measures to make sure all
customer-facing applications are better protected. Since there is a password to
access these applications, they want to monitor all password login attempts
for suspicious activity. One sign of suspicious
activity is having several failed login attempts within a short amount of time. You need to flag
users if they had more than three login failures
in the last 30 minutes. One way you could do this
in Python is by parsing a static txt log file with all user login attempts
to each machine. Python could structure the
information in this file, including the
username, IP address, timestamp, and login status. It could then use
conditionals to determine if a user
needs to be flagged. These are just a
few examples of how a security analyst might apply Python in their
day-to-day work. I hope you are as
excited as I am to create solutions
for security problems.

Reading: Essential Python components for automation

Reading

Video: Clancy: Continual learning and Python

Clancy’s Cybersecurity Journey: From Accounting to Google & Python Power

Meet Clancy, a Senior Security Engineer at Google:

  • Diverse Skills: Clancy transitioned from accounting to cybersecurity, emphasizing the variety of skills and knowledge needed in the field.
  • Everyday Excitement: No two days are alike in Clancy’s role, with new challenges and opportunities to utilize different skillsets.
  • Python Prowess: Python is Clancy’s go-to language at Google, praised for its power and script-writing potential.
  • Learning Python: Clancy encourages starting with resources, side projects, and embracing the “Pythonic way” of doing things.
  • Continuous Growth: The ever-evolving nature of Python and cybersecurity requires constant learning and project-based growth.
  • Fun & Fundamentals: Clancy’s advice for beginners: make learning fun, develop a cybersecurity baseline, and then deep dive into specific interests.
  • Perseverance Pays Off: The learning journey can be challenging, but perseverance and dedication lead to a rewarding career in cybersecurity.

This summary captures the key points of Clancy’s story, highlighting:

  • His non-traditional path to cybersecurity.
  • The excitement and diversity of the field.
  • The importance of Python and learning resources.
  • Clancy’s tips for beginner Python learners and cybersecurity aspirants.
  • The message of perseverance and dedication to achieve success.

My name is Clancy and I’m a
Senior Security Engineer. My team here at
Google is part of an ongoing effort to protect Google’s sensitive information,
customer data, PII. Everyday is different at my job, it allows me to use
different skills, knowledge sets, and
no day is alike. By trade, I am not a engineer or software
engineer at all. I was actually in
accounting. Being affected by any type of cybersecurity attack
definitely gives you a perspective on
the opposite side. You get to see how
this affects users, how this affects people
that were attacked. Had I known when I
first started out how big of a field
cybersecurity really was, it would have allowed
me to explore. Python is a
developmental language. I use it very frequently
at my role at Google. One of my favorite things about Python is the power
of the language. You can use it to create very powerful scripts that you’ll use in your
day-to-day role. When I first picked up Python, the trickiest part
was learning how to say things the Pythonic way. I used various resources
online as well as books, as well as picking
up side projects. One of the best things
about Python it’s a very widely used
language and you can find many resources online
depending on your skill set. Python, as well as any other developmental language,
is constantly evolving. Continue to take on projects, continue to stretch
your knowledge and you’ll continue to grow. The advice I can
give for a person starting to learn
Python is make it fun. I think once you find a
learning a language to be fun, it allows you to
be more engaged. Develop a good baseline
for what cybersecurity is. Make yourself a little well-rounded in the beginning
and then from there you can branch out and deep dive into subjects that are
interesting to you. When starting out,
it can be very tough and you feel as if you’re
climbing up a big hill. Persevere, continue to learn and it will be a very
rewarding experience.

Practice Quiz: Test your knowledge: Python and automation

Which of the following potential signs of suspicious activity can you track with automated Python programs? Select all that apply.

Which Python component contributes to automation by allowing you to perform the same actions a certain number of times based on a sequence?

Why is knowing how to work with files important for automation?

Which of the following are common file formats for security logs? Select all that apply.

Work with files in Python


Video: Access a text file in Python

Summary of Python File Reading for Security Professionals:

Key Points:

  • Security Professionals and Log Files: Analyzing log files is crucial for security, but manual review can be time-consuming, hence Python’s automation potential.
  • Using the with Statement:
    • Handles resource management and error handling automatically.
    • Ensures files are closed properly after reading.
  • Opening Files with open():
    • Basic syntax: with open(filename, mode) as file:
    • filename: Path to the file, including extension (e.g., .txt).
    • mode: Specifies the operation (e.g., "r" for reading, "w" for writing).
  • Reading File Contents with read():
    • Converts file content into a string.
    • Example: file_content = file.read()
  • Indentation for with Statements:
    • Code within a with statement must be indented, similar to loops.

Next Up:

  • Parsing files for detailed analysis of security logs.

Python File Reading for Security Professionals: Automate Log Analysis

Welcome, Security Aficionados!

In this tutorial, you’ll master Python’s file-reading skills to streamline your log analysis tasks. Ready to automate and conquer those hefty log files? Let’s dive in!

Key Tools for the Job:

  • with Statement: Your trusty sidekick for handling resources efficiently and gracefully. It ensures files are closed properly, preventing potential errors.
  • open() Function: The gate-opener to file access. Use it to specify the file you want to work with and the mode of operation (reading or writing).
  • read() Method: The content extractor. It converts file content into a string, ready for your analysis.

Step-by-Step Guide:

  1. Import the Necessary Libraries: If you’re dealing with specific file formats (e.g., CSV), import relevant libraries like csv.
  2. Open the File:
    • Construct the with open() statement:
with open("filename.txt", "r") as file:
    # Code to work with the file goes here

Replace "filename.txt" with the actual file path and name.

Use "r" for reading, "w" for writing, and other modes as needed.

  1. Read the File Contents:
    • Within the indented block of the with statement, use read():
file_contents = file.read()
  1. This stores the file content as a string in the file_contents variable.
  2. Process the Data:
    • Analyze the file_contents string using string manipulation techniques, regular expressions, or data parsing techniques.
    • Extract relevant information, identify patterns, or search for specific events.

Example: Printing File Contents:

Python

with open("security_log.txt", "r") as log_file:
    log_data = log_file.read()

print(log_data)

Remember:

  • Indentation is crucial in Python! Code within the with statement must be indented.
  • Close files properly to avoid resource issues. The with statement handles this automatically, but it’s good practice to be mindful of file management.

Next Steps:

  • Explore parsing techniques to extract specific information from log files, such as timestamps, IP addresses, or event details.
  • Learn about different file formats (CSV, JSON, etc.) and how to handle them in Python.
  • Practice with real-world security logs to hone your skills and create powerful automation scripts!

Happy Security Automating!

What does the line of code with open("ip_addresses.txt, "r") as file: instruct Python to do? Select two answers.
  • Open the “ip_addresses.txt” file in order to read it
  • Store the file object in the file variable while inside the with statement

The line of code with open(“ip_addresses.txt, “r”) as file: instructs Python to open the “ip_addresses.txt” file in order to read it (“r”). It also instructs Python to store the file object in the file variable while inside the with statement.

Security professionals are often
tasked with reviewing log files. These files may have thousands of entries, so it can be helpful to automate this
process, and that’s where Python comes in. Let’s start by importing a simple text
file that just contains a few words and then restoring it as a string in Python. All we need is the text file, its
location, and the right Python keywords. We’re going to start by
typing a “with” statement. The keyword with handles errors and
manages external resources. When using with, Python knows to
automatically release resources that would otherwise keep our system busy
until the program finishes running. It’s often used in file
handling to automatically close a file after reading it. To open files and then read them,
we write a statement that begins with the keyword with.
Then, we use the open() function. Open() is a function that
opens a file in Python. The first parameter is the name of
the text file on your computer or a link to it on the internet. Depending on the Python environment, you might also need to
include a path to this file. Remember to include the .txt
extension in the file name. Now let’s discuss the second parameter. This parameter in the open() function tells
Python what we want to do with the file. In our case, we want to read a file, so we
use the letter “r” between quotation marks. If we wanted to write to a file,
we would replace this “r” with a “w”. But here, we’re focusing on reading. Finally, file is a variable that contains the file information as long as
we’re inside the with statement. Like with other types of statements, we
end our with statement with a colon. The code that comes after the colon
will tell Python what to do with the content of the file. Let’s go into Python and
use what we learned. We’re ready to open a text file in Python. Now we’ll type our with statement. Next, we’ll use Python’s
built-in read method. The read method converts
files into strings. Now let’s go back to our with statement. Similar to a for loop, with statements
start an indent on the next line. This tells Python that this code is
happening inside the with statement. Inside of the statement, we’re going
to use the read() function to turn our file into a string and
store that inside a new variable. This new variable can be used
outside of the with statement. So let’s exit the with statement
by removing the indentation and print the variable. Perfect! The string from
the text prints out. Coming up,
we’re going to discuss parsing files so we are equipped to handle
security logs in the future.

Reading: Import files into Python

Reading

Video: Parse a text file in Python

Summary of Parsing Text Files in Python:

Key Points:

  • Parsing: Converting data into a more structured and readable format for analysis.
  • The split() Method:
    • Converts a string into a list.
    • Separates the string based on a specified character (or whitespace if no argument is given).
  • Example with Security Log:
    • Each line represents a data point.
    • Use split() without an argument to separate lines (using newline as a delimiter).
  • Steps:
    1. Open the file with open().
    2. Read the contents into a string with read().
    3. Use split() to create a list of lines.
    4. Assign the list to a variable for further use.

Next Up:

  • Exploring techniques for working with data in Python more in-depth.

Parsing Text Files in Python: Unleashing Data for Analysis

Welcome, Python Data Explorers!

Ready to unlock the secrets hidden within text files? Let’s dive into parsing, the art of transforming raw text into structured data ready for your analytical wizardry!

Key Tools:

  • open() Function: Your trusty file opener, providing access to the textual treasures.
  • read() Method: The content extractor, converting file content into a string for further manipulation.
  • split() Method: The string-slicing master, transforming a string into a list, expertly separating elements based on specified characters or whitespace.

Step-by-Step Guide:

  1. Open the File:
    • Use with open() to ensure proper file handling:
with open("filename.txt", "r") as file:
    # Code to work with the file goes here

Replace "filename.txt" with the actual file path.

  1. Read the Contents:
    • Apply read() to capture the file’s contents as a string:
file_contents = file.read()
  1. Unleash the split() Method:
    • Transform the string into a list for structured analysis:
parsed_data = file_contents.split()  # Split based on whitespace
  1. Customize separation by specifying a delimiter:
parsed_data = file_contents.split(",")  # Split based on commas
  1. Assign and Analyze:
    • Store the parsed data in a variable:
usernames = parsed_data  # Example using the security log example
  1. Explore and analyze the list using Python’s data analysis techniques!

Example: Parsing a Security Log:

Python

with open("security_log.txt", "r") as log_file:
    log_data = log_file.read()
    usernames = log_data.splitlines()  # Split based on newlines

print(usernames)

Remember:

  • Indentation matters! Code within the with statement must be indented.
  • Choose delimiters wisely based on the file’s structure.
  • Explore other string manipulation methods for advanced parsing tasks.

Next Steps:

  • Practice with diverse text files to refine your parsing skills.
  • Delve into regular expressions for complex pattern matching and extraction.
  • Discover Python’s data analysis libraries (like Pandas) to unleash your analytical superpowers!

Happy Parsing and Data Exploration!

Now that you know how to
import text files into Python, we’re going to
take this one step further and learn how to
give them a structure. This will allow us to
analyze them more easily. This process is often
referred to as parsing. Parsing is the process of converting data into a
more readable format. To do this, we’re going to put together everything
we learned about lists and strings and learn another method for working
with strings in Python. The method we need
is the split method. The split method converts
a string into a list. It does this by separating the string based on a
specified character. Or, if no argument is passed, every time it encounters
a whitespace, it separates the string. So, a split would
convert the string “We are learning about
parsing!” into this list. We are using the split method to separate the strings into smaller chunks that
we can analyze more easily than one
big block of text. In this video, we’ll
work with an example of a security log where every line represents
a new data point. To store these points in a list, we want to separate the
text based on the new line. Python considers a new line
to be a type of whitespace. We can use the split method
without passing an argument. We’ll start with our code
from the previous video. Remember, we used
this code to open a file and then read
it into a string. Now, let’s split
that string into a list using the split method
and then print the output. After we run it, Python outputs a list of usernames instead of
one big string of them. If we want to save this list, we would need to assign
it to another variable. For example, we can call
the variable usernames. And then we’ll run it again. And now this list can be
reused in other code. Congratulations! You just learned the basics of parsing a text file in Python. In the next videos, we’re
going to be exploring techniques that help us work more in depth
with data in Python.

Reading: Work with files in Python

Reading

Lab: Activity: Import and parse a text file

Lab: Exemplar: Import and parse a text file

Video: Develop a parsing algorithm in Python

Summary of Suspicious Login Attempt Detection in Python:

Key Points:

  • Goal: Create a program to detect suspicious login attempts (3 or more failed attempts).
  • Inputs:
    • Text file with failed login attempts (one username per line).
    • Username of the current user logging in.
  • Steps:
    1. Import the log file and parse it into a list of usernames.
    2. Define a function login_check(login_list, current_user).
    3. Initialize a counter variable to 0.
    4. Iterate through the login_list using a for loop.
    5. Inside the loop, check if the current username in the list matches the current_user.
      • If yes, increment the counter.
    6. After the loop, check the counter:
      • If counter >= 3, print “Account locked.”
      • Else, print “User can log in.”
  • Example Usage:
usernames = ["elarson", "eraab", "tjones", "eraab", ...]  # Example list
login_check(usernames, "eraab")  # Output: "Account locked."
login_check(usernames, "elarson")  # Output: "User can log in."

Key Concepts:

  • File parsing with open() and split().
  • Using for loops for iteration.
  • Employing if statements for conditional logic.
  • Counter variables to track occurrences.

Next Steps:

  • Explore ways to make the algorithm more efficient.
  • Apply the concept to other security-related tasks.
  • Continue learning and growing Python skills!

Tutorial: Suspicious Login Attempt Detection in Python

Welcome, Python Security Guardians!

Ready to protect your digital realms from potential intruders? Let’s dive into crafting a Python program that vigilantly detects suspicious login activity!

Tools of the Trade:

  • File Handling: open() to unlock file secrets, read() to extract content, and split() to parse data into a list.
  • Loops: for loops to iterate through lists like a vigilant watchman.
  • Counters: Variables to track occurrences, keeping a watchful eye on failed attempts.
  • Conditionals: if statements to make decisive judgments, determining when to lock accounts.

Step-by-Step Guide:

  1. Import the Log File:
    • Utilize open() to access the log file containing failed login attempts.
    • Read its contents using read().
    • Employ split() to create a list of usernames, separating those who’ve stumbled at the login gates.
  2. Define the login_check() Function:
    • Craft a function named login_check(), accepting two parameters:
      • login_list: The list of failed login attempts, your roster of potential mischief-makers.
      • current_user: The username of the individual currently attempting to enter, awaiting your judgment.
  3. Initialize the Counter:
    • Within the function, create a counter variable, starting at 0, to track the current user’s failed attempts.
  4. Unleash the for Loop:
    • Initiate a for loop to iterate through each username in the login_list, scrutinizing them one by one.
  5. Employ if Statements for Identification:
    • Within the loop, employ an if statement to compare the current username in the list with the current_user.
    • If they match, increment the counter, raising a red flag for potential foul play.
  6. Pass Judgment with if-else:
    • After the loop concludes its vigilant inspection, deploy a final if-else statement to determine the verdict:
      • If the counter has reached 3 or more, print “Account locked.” – The intruder has been thwarted!
      • Otherwise, print “User can log in.” – The individual has passed your scrutiny.

Example Usage:

Python

# Example list of failed login attempts
usernames = ["elarson", "eraab", "tjones", "eraab", ...]

# Test for a user with multiple failed attempts
login_check(usernames, "eraab")  # Output: "Account locked."

# Test for a user with fewer attempts
login_check(usernames, "elarson")  # Output: "User can log in."

Remember:

  • Indentation is paramount in Python, ensuring clarity in your code’s execution.
  • Explore more efficient algorithms as your skills evolve, continuously fortifying your security defenses.
  • Apply this concept to other security measures, such as detecting unusual activity patterns or identifying potential vulnerabilities.

Continue your Python security journey with confidence, knowing you’ve laid a solid foundation for protecting your digital domains!

# Open, read, and split a text file
with open["login_attempts.txt. "r") as file:
     file_text = file.read()
usernames = file.txt.split()

# Create a function that counts a user's failed login attempts
def login_check(login_list, current_user):
     counter = 0
     for i in login_list:
          if i == current_user:
               counter = counter + 1
     if counter >= 3:
          return "You have tried to login three or more times. Your account has been locked."
     else:
          return "You can log in!"

login_check(username, "elarson")

We’re now going to bring all of
the pieces together to import a file, parse it, and implement a simple algorithm to
help us detect suspicious login attempts. In this video, we want to create
a program that runs every time a new user logs in and checks if that user has had three or
more failed login attempts. First, let’s discuss the structure
of our inputs to build a strategy to develop our program. We have a log file stored in a .txt format
that contains one username per line. Each username represents
a failed login attempt. So when a user logs in, we want our
program to check for their username and count how many times that
username is in our log file. If that username is repeated three or
more times, the program returns an alert. We’ll start with code that imports
the file of logging attempts, splits it, and stores it
into a variable named usernames. Let’s try printing the variable user
names to check for its contents. We’ll run this. Perfect!
This is exactly what we expected. The variable usernames is ready
to be used in our algorithm. Now let’s develop a strategy for counting
username occurrences in the list. We’ll start with the first eight
elements of the usernames list. We notice that there are two
occurrences of the username “eraab” in the list, but
how would we tell Python to count this? We’ll implement a for loop that
iterates through every element. Let’s represent the loop
variable with an arrow. We’ll also define a counter
variable that starts at 0. So, our for loop starts at
the username “elarson.” At every element, Python asks, “Is this element equal to the string
‘eraab’?” If the answer is yes,
the counter goes up by one. If it isn’t,
then the counter stays the same. Since “elarson” is not
the same as “eraab,” the counter remains 0. Then, we move on to the next element. We encounter our first
occurrence of “eraab.” At this point, the counter
increases by 1. As we move to the next element,
we find another occurrence of “eraab,” so we increase our counter by 1 again. That means that our counter is now at 2. We will continue this process for
the rest of the list. Now that we know the solution, let’s talk
about how to implement it in Python. Solving the problem in Python
will involve a for loop, a counter variable, and an if statement.
Let’s get back into our code. We’ll create a function that counts
a user’s failed login attempts. First, let’s define our function.
We’ll call it login_check(). It takes two parameters.
The first is called login_list. This will be used for
the list of failed login attempts. The second is called current_user. This
will be used for the user who logs in. Inside of this function,
we start by defining the counter variable and
set its value to 0. Now we start the for loop.
We’ll use i as our loop variable and iterate through the login list. In other words, as the loop iterates, it will run through all the failed
login attempts in the list. Directly inside of the for loop, we
start the if statement. The if statement checks if our loop variable is equal to
the current_user we’re searching for. If this condition is true,
We want to add 1 to the counter. We’re almost done with our algorithm. Now, we just need the final if-else
statement to print the alert. If the counter adds up to 3 or more, we need to tell the user that their
account is locked so they can’t log in. We’ll also type an else statement for users
who can log in. Our algorithm is complete! Let’s try out our new function
on an example username. We can pull out a few of the usernames
in the list and try our function on them. Let’s use the first name in the list. Let’s run the code. According to our code, this user can log in. They have fewer
than three failed login attempts. Now let’s go back to our user “eraab.” Remember, they had two entries in
the list of the first eight names in our failed login attempts. Do you think they’ll be able to log in?
When we run, we get an “account locked” message.
This means they had three or
more failed login attempts. Excellent work! You’ve just developed your
first security algorithm involving a log. As you grow in your skills, you’ll learn
how to make this algorithm more efficient, but this solution works well for now. In this video,
we recapped everything we learned so far, from list operations to algorithm
development, all the way to file parsing. We did this while building an algorithm
we can apply in a security context.

Lab: Activity: Create another algorithm

Lab: Exemplar: Create another algorithm

Quiz: Portfolio Activity: Update a file through a Python algorithm

Reading: Portfolio Activity Exemplar: Update a file through a Python algorithm

Reading

Practice Quiz: Test your knowledge: Work with files in Python

You want to open the file “logs.txt” and store it in the file variable for the purpose of reading it. You also want to ensure all resources are released and the file is closed after you read it. What is the correct line of code to do this?

After you’ve opened a log file as login_file, which line of code can you use to read the file and store it in a variable called login_attempts?

You just read a log file into a variable called file. The file variable contains a string of multiple IP addresses that are each separated by a whitespace. Which line of code separates each individual IP address and stores it as a list in a variable called ip_addresses?

You need to check for unusual login activity. Specifically, you need to check a list of login timestamps to determine if any of the login times occurred at unusual hours. If you want to automate this through Python, what would be part of your code? Select two answers.

Debug Python Code


Video: Debugging strategies

Summary of debugging techniques for Python code:

Types of errors:

  • Syntax errors: Incorrect language usage (missing colon, misspelled keyword, etc.). Easy to fix based on error message and location.
  • Logic errors: Unintended results. No error message, requires examining output or using print statements and debuggers.
  • Exceptions: Unexpected events (dividing by zero, out-of-range index). Error message indicates issue.

Debugging strategies:

  • Print statements: Add temporary statements to track code execution and identify problematic sections.
  • Debuggers: Set breakpoints to run code in smaller segments and pinpoint errors.
  • Error messages: Analyze them to understand the type and location of the issue.

Remember:

  • Debugging is crucial for writing functional Python code.
  • Different techniques are suitable for different error types.
  • Practice these techniques to become a more effective Python programmer.

Debugging Python Code: Your Guide to Conquering Errors

Welcome to the Debugging Dojo! Ready to master the art of fixing code glitches? Let’s dive into battle-tested techniques to make your Python programs shine.

Meet Your Opponents:

  • Syntax Errors: These grammar gremlins cause immediate errors due to incorrect language usage. Think missing colons, misspelled keywords, or unclosed parentheses.
  • Logic Errors: These sneaky ninjas produce unintended results without clear error messages. They often stem from flaws in your code’s logic, like using the wrong operators or variables.
  • Exceptions: These unexpected events halt your code, such as dividing by zero or accessing a non-existent index. They usually provide error messages to guide you.

Your Arsenal of Weapons:

  1. Print Statements: Your trusty sidekicks for tracking code execution. Scatter them strategically to reveal variable values and pinpoint problematic areas.
  2. Debuggers: Your superpower for in-depth analysis. Use them to pause code execution, inspect variables, and step through code line by line. Popular debuggers include:
    • Built-in pdb module
    • IDE-specific debuggers (e.g., PyCharm, Visual Studio Code)
  3. Error Messages: Your wise advisors, providing clues about error types and locations. Learn to decipher their cryptic language for valuable insights.

Battle Strategies:

  1. Syntax Errors:
    • Read error messages carefully for hints about line numbers and error types.
    • Double-check common syntax pitfalls (e.g., indentation, parentheses, semicolons).
    • Use a linter or code formatter to catch potential errors early on.
  2. Logic Errors:
    • Test code thoroughly with various inputs to expose unexpected behavior.
    • Employ print statements to visualize variable values and code flow.
    • Use a debugger to step through code and examine variables at each stage.
    • Break code into smaller, testable functions for easier debugging.
  3. Exceptions:
    • Analyze error messages to understand the issue and its context.
    • Use try-except blocks to handle potential exceptions gracefully.

Mastering the Art:

  • Practice Patience: Debugging can be time-consuming, but persistence pays off.
  • Isolate Issues: Divide and conquer by testing smaller code sections independently.
  • Think Logically: Trace code execution step by step, mentally simulating its behavior.
  • Seek Help: Don’t hesitate to consult online resources, communities, or fellow Pythonistas for guidance.

Remember:

  • Debugging is an essential skill for any Python programmer.
  • The more you practice, the more comfortable you’ll become with identifying and fixing bugs.
  • Embrace the challenge and enjoy the satisfaction of conquering those pesky errors!

Happy debugging, code warrior! ⚔️

Which of the following are syntax errors? Select two answers.
  • Misspelling the Python keyword elif by typing elsif instead
  • Omitting the colon at the end of an iterative statement header

Omitting the colon at the end of an iterative statement header and misspelling the Python keyword elif by typing elsif instead are two examples of syntax errors. Syntax errors involve invalid usage of the Python language.

As a security analyst, you might be required
to read or write code. One of the biggest challenges is getting it to run and
function properly. In fact, fixing
complex errors in code can sometimes
take up just as much, if not more, time than
writing your code. This is why it’s important
to develop this skill. Now that you’ve learned the
basics of coding in Python, it’s important to learn
how to deal with errors. For that reason, we’ll focus
on debugging your code. Debugging is the practice of identifying and fixing
errors in code. In this video, we’ll explore
some techniques for this. There are three types of errors: syntax errors, logic
errors, and exceptions. Syntax errors involve
invalid usage of the Python language, such as forgetting to add a colon after
a function header. Let’s explore this
type of error. When we run this code, we get a message that indicates
there’s a syntax error. Depending on the
Python environment, it may also display
additional details. We’ll typically get
information about the error, like its location. These syntax errors
are often easy to fix since you can find exactly
where the error happened. They are similar to correcting simple grammar
mistakes in an email. Since their message tells
us the problem is on the line that defines the
function, let’s go there. In this case, we can add a colon to the header
and resolve our error. When we run it again, there’s no longer
an error message. This is just one example
of a syntax error. Other examples include omitting a parenthesis after a function, misspelling a Python keyword, or not properly closing
quotation marks for a string. Next, let’s focus
on logic errors. Logic errors may not
cause error messages; instead, they produce
unintended results. A logic error could be
as simple as writing the incorrect text within
a print statement, or it might involve
something like writing a less than symbol instead of less than or equal to symbol. This change in
operator would exclude a value that was needed for
the code to work as intended. For example, imagine that you reach out to
a response team when the priority level of
an issue is less than three instead of less
than or equal to three. This means all
events classified as priority level 3 could go
unnoticed and unresolved. To diagnose a logic error
that’s difficult to find, one strategy is to
use print statements. You’ll need to insert print statements
throughout your code. The print statements should describe the location
in the code; for example, “print line 20” or “print line 55: inside
the conditional”. The idea is to use these
print statements to identify which sections of the code are
functioning properly. When a print statement doesn’t print as expected, this helps you identify sections of the
code with problems. Another option for identifying logic errors is to
use a debugger. A debugger will let you insert breakpoints
into your code. Breakpoints allow you to
segment your code into sections and run just
one portion at a time. Just like with the
print statements, running these sections
independently can help isolate
problems in the code. Let’s move on to our last
type of error: an exception. Exceptions happen when the
program doesn’t know how to execute code even though there are no problems
with the syntax. Exceptions occur for a variety
of reasons. For example, they can happen when
something is mathematically impossible, like asking the code to divide something by 0. Exceptions might
also happen when you ask Python to access
index values that don’t exist or when Python doesn’t recognize variable
or function names. Exceptions also may occur when you use an
incorrect data type. Let’s demonstrate an exception. Let’s say you have
a variable called my_string that contains
the word “security”. Since this string
has 8 characters, we can successfully print
any index less than 8. Index 0 contains “s.” Index 1 contains “e.” And index 2 contains “c.” But, if you try to
access the character at index 100, you’ll
get an error. Let’s run this and
explore what happens. After it successfully prints
the first three statements, we get an error message: “string index out of range.” For exception errors, you can also make
use of debuggers and print statements to figure out the potential
source of error. Errors and exceptions can be expected when
working in Python. The important thing is to
know how to deal with them. Hopefully, this video provided some valuable insight
about debugging code. This will help
ensure that the code that you write is functional.

Video: Matt: Learning from mistakes

Summary of Matt’s Cybersecurity Journey:

From Music to Hacking:

  • Matt initially pursued music (jazz trombone) but switched to software engineering in cybersecurity.
  • He finds inspiration in movies like The Matrix, despite their unrealistic portrayal of the field.

Embracing Errors as Learning Opportunities:

  • Matt views coding errors as chances to learn and expand his knowledge, not failures.
  • He cites this as a key difference between a good and a great software engineer.

Solving a Messy Fingerprinting Problem:

  • Matt encountered frustrating errors while fingerprinting vulnerabilities at Google.
  • Debugging them was tough but ultimately rewarding, highlighting the resilience needed in cybersecurity.

Advice for Struggling Cybersecurity Professionals:

  • Don’t give up – the feeling of solving complex problems is incredible.
  • Don’t be afraid to ask for help – others are often excited to contribute to challenging issues.

Enthusiasm for Cybersecurity:

  • Matt emphasizes the growing importance of cybersecurity and the constant stream of new challenges and opportunities.
  • He encourages others to explore this exciting field.

Key Takeaways:

  • Matt’s personal journey highlights the unique and rewarding aspects of cybersecurity work.
  • His focus on learning and perseverance provides valuable insights for aspiring cybersecurity professionals.
  • The field offers continuous learning and a chance to make a real impact on the world.

This summary captures the essence of Matt’s story and his passion for cybersecurity. It aims to inspire and inform those interested in exploring this dynamic field.

My name is Matt. I’m a software engineer
working in cybersecurity. When I was in high school, what I really want
to do is music, I was a musician. I went to music school
for jazz trombone. Partway through that
process, I realized, no, bandleader in their right mind, looks at a group and thinks, we need a trombone player. This is what makes us better. I grew up watching
movies like The Matrix, and it’s not very realistic to what cybersecurity
work actually is, but it is inspiring. If you dig through the work at specifics of what
you do and take the broad step back like you are that cool guy with
sunglasses, you’re a hacker. When I first started
writing code, I would look at coding errors as a sign that I have done bad. But as I grew older, a little bit more mature, I realized everyone
has coding errors. Literally the very best
software engineer I know writes code
and it has errors. Errors represent a moment where you can take a step back and
say, what did I do wrong? It’s a learning opportunity. Now, I see these
like moments where I can look at some
problems that I don’t understand and be like, why? Dive into it and expand my knowledge of computer
science, which is my whole job. I see this as a learning process and it’s
a little bit fun. One of the really messy coding
areas that I’ve run into in my time here at Google
involved fingerprinting when we find a vulnerability. If we find the same
vulnerability later, we don’t want to have
two vulnerabilities, we don’t want to poke
someone twice and be like, fix this thing if it’s
the exact same thing. We do this thing called fingerprinting where we
say this vulnerability has a specific fingerprint
and if we find another vulnerability that
has the same fingerprint, we’re not going to store them separately or treat
them separately. They’re effectively the same. I was running into these errors where things would not fingerprint in the way
that I expected them to. I was literally grinding
my gears for weeks, trying to figure out what is going on with this thing? But when I found it was very
satisfying like, that’s it. When you’re in the
middle of this mess, all of that self-doubt
creeps into your brain. You’re like, maybe I’m not as good at this thing
as I thought I was. What I would go back and tell myself: A), it’s not endless – it gets better. Once
you figure it out, that feeling of
reward is incredible. But B), also, it’s okay
to rope people in if you are struggling
with something, I always advocate
for asking for help. Most people are really excited to go help you
out with this thing, especially when it’s
a convoluted problem. I am so thrilled I ended
up in cybersecurity. Cybersecurity is
having its moment. People are realizing, waking
up to the amount of data that they’re putting out into the world and they’re
starting to care about it. Every day there’s something new. Every day there’s something exciting for me to do and yeah, get into it.
Cybersecurity is the way.

Video: Apply debugging strategies

Here’s a summary of the debugging process demonstrated in the video:

Code Purpose:

  • Parses lines from a log file tracking software application issues.
  • Excludes lines with status code 200 (successful events) from parsing.

Errors Encountered and Solutions:

  1. Syntax Error: Missing colon in function header. Fixed by adding the colon.
  2. Name Error: Misspelled variable application_name. Fixed by correcting the spelling.
  3. Logic Error: Code parsed lines with status code 200 instead of returning “Successful event – no parsing needed.” Fixed by moving the if statement checking for status code 200 before the return parsed_line statement.

Debugging Strategies Employed:

  • Reading Error Messages: Identified error types and locations.
  • Print Statements: Tracked code execution and pinpointed logic error.
  • Understanding Code Logic: Recognized that the return statement was exiting the function before the status code check.

Key Takeaways:

  • Debugging involves identifying and fixing errors to ensure code works as intended.
  • Different error types require different approaches.
  • Understanding code logic is crucial for effective debugging.
  • Print statements and careful code examination are valuable debugging tools.
  • Even when code runs without errors, verify that it produces the expected output.

Let’s say our co-workers need some help getting
their code to work, and we’ve offered to debug
their code to make sure it runs smoothly. First, we need to know about
the purpose of the code. In this case, the purpose
of the code is to parse a single line from
a log file and return it. The log file we’re using tracks potential issues with
software applications. Each line in the log contains the HTTP response status codes, the date, the time, and the application name. When writing this code, our co-workers consider whether all these status codes
needed to be parsed. Since 200 signals a
successful event, they concluded that lines with this status code
shouldn’t be parsed. Instead, Python should
return a message indicating that
parsing wasn’t needed. To start the debugging
process, let’s first run the code to identify
what errors appear. Our first error is
a syntax error. The error message also tells us the syntax error occurs in a line that
defines a function. So let’s just scroll to
that part of the code. As you might recall, these function headers
should end with a colon. Let’s go ahead and
add that to the code. Now, the syntax error
should go away. Let’s run the code again. Now our syntax error is gone, which is good news, but we have another error, a
“name error.” “Name error” is actually
a type of exception, meaning we’ve written
valid syntax, but Python can’t
process the statement. According to the error, the interpreter
doesn’t understand the variable application_name
at the point where it’s been added
to the parsed_line list. Let’s examine that
section of code. This error means we haven’t assigned a variable
name properly. So now let’s go back to where it was first assigned and
determine what happened. We find that this
variable is misspelled. There should be two p’s in
application_name, not one. Let’s correct the spelling. Now that we’ve fixed it,
it should work. So let’s run the code.
Great! We fixed an error and an exception. And we no longer have
any error messages. But this doesn’t mean our
debugging work is done. Let’s make sure the logic of the program works as intended
by examining the output. Our output is a parsed line. In most cases, this
would be what we wanted. But as you might recall, if the status code is 200, our code shouldn’t parse the line. Instead, it should print a message that no
parsing is needed. And when we called it with
a status code of 200, there was a logic error because this message
wasn’t displayed. So let’s go back to the
conditional we used to handle the status code
of 200 and investigate. To find the source of the issue, let’s add print statements. In our print statements, we’ll include the line number and the description
of the location. We’ll add one print
statement before the line of code containing
“return parsed_list”. We’ll add another above the
if statement that checks for the 200 status code to determine if it reaches
the if statement. We’ll add one more
print statement inside the if statement to determine whether the
program even enters it. Now, let’s run the code and
review what gets printed. Only the first print
statement printed something. The other two print statements
after these didn’t print. This means the program didn’t even enter
the if statement. The problem occurred somewhere before the line that returns
the parsed_line variable. Let’s investigate. When Python encounters the
first return statement which sends back the parsed list, it exits the function. In other words, it
returns the list before it even checks for a
status code value of 200. To fix this, we must
move the if statement, checking for the status code somewhere before
“return parsed line”. Let’s first delete
our print statements. This makes the program
more efficient because it doesn’t run any
unneeded lines of code. Now, let’s move
the if statement. We’ll place it right
after the line of code that involves parsing the
status code from the line. Let’s run our code and confirm
that this fixed our issue. Yes! It printed “Successful
event – no parsing needed.” Great work! We’ve fixed
this logic error. I enjoyed debugging
this code with you. I hope this video has strengthened
your understanding of some helpful
debugging strategies and gave you an idea of some
errors you might encounter.

Reading: Explore debugging techniques

Reading

Lab: Activity: Debug Python code

Lab: Exemplar: Debug Python code

Practice Quiz: Test your knowledge: Debug Python code

What types of errors might you encounter while debugging code? Select three answers.

The purpose of this code is to indicate whether a particular operating system needs to be updated. However, it contains a syntax error. Run this code, analyze its output, and then debug it. (If you want to undo your changes to the code, you can click the Reset button.)

You have written code that assigns security incident tickets to the appropriate cybersecurity team based on its priority level. If the priority level is 1, it should get forwarded to Team A. If the priority level is 2, it should get forwarded to Team B. When testing your code, you notice that an incident with priority level 2 is forwarded to Team A instead of Team B. What type of error is this?

You have written code that uses a search algorithm to find an employee’s IP address. When testing your code, an error message indicates that an unknown index is being accessed. What type of error is this?

Review: Python in practice


Video: Wrap-up

This section covered essential Python skills for security professionals:

  • Opening and reading files: Crucial for analyzing log files, a staple of security work.
  • Parsing files: Navigating structured log files efficiently to extract desired information.
  • Debugging code: Troubleshooting errors as your code complexity grows, saving time and frustration.

The instructor expresses pride in your progress and emphasizes the exciting possibilities of applying Python to address security issues. This section equips you with valuable tools to tackle real-world security challenges through code.

Great work in this section! We focused on a few new
topics that will help you put Python into practice
in the security profession. First, we explored opening
and reading files in Python. Security analysts work
with a lot of log files, so the ability to do
this is essential. Next, we covered parsing files. Log files can be very long. For this reason, a structure in these files to make them more readable helps you automate your tasks and get the
information you need. And last, we focused
on debugging code. Knowing how to debug your code can save
you a lot of time, especially as your code
increases in complexity. Overall, I hope you feel proud of what you’ve
accomplished in this section. Addressing security
issues through Python is exciting, and the information we covered will allow
you to do that.

Reading: Reference guide: Python concepts from week 4

Reading: Glossary terms from module 4

Terms and definitions from Course 7, Module 4

Quiz: Module 4 challenge

What is debugging?

The purpose of the following code is to print the numbers from 0 to 9. Run this code, analyze its output, and then debug it. (If you want to undo your changes to the code, you can click the Reset button.)

The purpose of the following code is to iterate through a list and print a warning message if it finds “user3” in the list. Run this code, analyze its output, and debug it. (If you want to undo your changes to the code, you can click the Reset button.)

You did not assign a value to a variable before using it in a conditional statement. What type of error is this?

When debugging code, what are effective ways to determine which sections of code are working properly? Select all that apply.

Which of these functions or arguments should you include in a with statement if you want Python to open a file called access.txt so that it can be read? Select three answers.

The logins variable is a string containing 20 device IDs. The device IDs are separated by spaces. In order to pass it into a function that checks the login count of each device, the string should be divided into a list of separate IDs. How do you convert this string into a list and store it in a device_ids variable?

Fill in the blank: If you use the .split() method to convert a string into a list so that it can be read more easily, this would be an example of _____.

What does the following code do?
read_text = text.read()

You want to check for unusual login activity. Specifically, you want to check if there were more than three failed login attempts in the last 10 minutes by the last user who logged in. If you want to automate this through Python, what would be part of your code? Select three answers.

Congratulations on completing Course 7!


Video: Course wrap-up

Python Masterclass: A Look Back and a Look Forward

Congratulations! This summary highlights the key takeaways from your Python journey:

Foundations Laid:

  • Basics: Variables, data types, conditionals, and loops – the building blocks of Python!
  • Crafting Code: Writing efficient, reusable code through functions, both built-in and custom.
  • Building with Blocks: Leveraging modules and libraries for pre-packaged functionality.
  • Readability Matters: Keeping your code clean and clear for ease of future understanding.

Data Dive:

  • String & List Savvy: Mastering methods, indices, and slicing for string and list manipulation.
  • Algorithm Adventures: Putting it all together to write a simple algorithm.
  • Pattern Power: Utilizing regular expressions to find information within strings.

Security Focus:

  • Real-World Files: Reading, parsing, and analyzing logs, a crucial skill for security professionals.
  • Debugging Demystified: Learning to identify and fix errors in your code, keeping it running smoothly.

The Road Ahead:

  • Practice Makes Perfect: Keep up the good work! Rewatching and exercising these concepts will solidify your knowledge.
  • Join the Python Security Force: Apply your new skills to tackle real-world security challenges.

This course equipped you with valuable Python skills for the security field. Remember, the learning journey continues – keep practicing, exploring, and contributing to the exciting world of Python security!

As we wrap up this course, I want to congratulate you for your commitment to
learning Python. You should feel accomplished
having explored a programming language that’s useful in the security field. Let’s recap some of
what we’ve learned. First, we covered basic
programming concepts in Python. We discussed
variables, data types, conditional statements,
and iterative statements. These topics provided
important foundations for what we explored
later in the course. And our next focus was on writing
effective Python code. We learned how we can
reuse functions in our programs to
improve efficiency. We explored built-in
functions and even created our own
user-defined functions. Another topic was
modules and libraries. The pre-packaged functions
and variables they contain can make
our work easier. Last, we learned ways to
ensure our code is readable. In the next section, we focused on working
with strings and lists. We learned a variety of methods that can be
applied to these data types. We also learned about their
indices and how to slice characters from a string
or elements from a list. We put all of these together to write a simple algorithm, and then we explored how regular expressions can be used to find patterns in the strings. And last, we wrapped
up the course with a focus on putting
Python into practice. We learned how to open, read, and parse files. With these skills,
you can work with a variety of logs you will encounter in a security setting. We also learned
how to debug code. This is an important skill
for all programmers. Wow! You learned a lot about Python in this
course, so great job! I hope soon you’ll join me in using Python in the
security profession. In the meantime, I
encourage you to practice, and feel free to rewatch these videos
whenever you like. The more you study
these concepts, the easier they will become. Thanks again for joining
me as we explored Python.

Reading: Reference guide: Python concepts from Course 7

Reading: Course 7 glossary