INTRODUCTION – Python in Practice
In this segment of the course participants will learn how to apply python practically in the field of cyber security and automate the most crucial tasks related to file handling. The module will start with files, thus opening and reading them, and presents a primary sense of how to deal with other types of file formats. It will then move on to file parsing and its content organization, which will allow participants to leverage their skills in deriving insights from different types of data sources.
This is an import aspect of this module on debugging code for participants on how to identify and fix faults in Python programs. This application-based learning will ensure that students become proficient in the use of Python and enhance their skills in problem-solving in cybersecurity automation. Participants will thus learn from this entire exposure to apt practices using Python in the manipulation and automation of file processes in effective scripting for cyberspace.
Learning Objectives
- Automate tasks done by a security professional most commonly using Python.
- Open and read a file with Python.
- Parsing a file using Python.
Debug code.
TEST YOUR KNOWLEDGE: PYTHON AND AUTOMATION
1. Which of the following potential signs of suspicious activity can you track with automated Python programs? Select all that apply.
- Whether login attempts occurred from IP addresses that are not established work zones (CORRECT)
- Whether login attempts occurred outside of normal work hours (CORRECT)
- Whether phishing attempts occurred through in-person interactions
- Whether several failed login attempts occurred within a short span of time (CORRECT)
With the help of automated Python programs, you will be able to monitor several possible security threats such as tracking several failed login attempts within a given duration, identifying login attempts outside of normal working hours, and detecting login attempts from outside country-specific work zones. Under all these conditions, Python will be able to collect and analyze all required data for automation, thus making the security monitoring process more efficient and proactive.
2. Which Python component contributes to automation by allowing you to perform the same actions a certain number of times based on a sequence?
- Conditional statements
- for loops (CORRECT)
- while loops
- Bracket notation
You can reduce the repetition in Python by using for loops by replicating the same action several times according to the same sequence. Use this to iteratively traverse lists, ranges or other iterable objects, thus automating tasks that otherwise require repeating the same code several times.
3. Why is knowing how to work with files important for automation?
- Cybersecurity-related information is often found in log files. (CORRECT)
- In order to create a function, it’s necessary to incorporate a file into it.
- String and list methods are only accessible through files.
- It is necessary to save a file in order to review what you have automated.
Knowing how to handle files becomes important for automating most of what concerns cybersecurity information, which is often collected in log files: login attempts, or any events related to the system and alerts pertaining to security. The reading, parsing, and analyzing of log files enables one to rapidly identify and respond to security threats, making file handling vital for the cybersecurity worker.
4. Which of the following are common file formats for security logs? Select all that apply.
- .txt (CORRECT)
- .csv (CORRECT)
- .jpeg
- .gif
The familiar formats for security logs are .txt and .csv. They are both text types, which means i.e., they contain plain text and not complex lines. As a result, it becomes easy to extract and process data contained .txt and .csv because the number of log entries can be automated for simple analysis, pattern identification, and detection of security incidents.
5. What does the line of code with open(“ip_addresses.txt, “r”) as file: instruct Python to do? Select two answers.
- Create a new file called “ip_addresses.txt”
- Open the “ip_addresses.txt” file in order to read it (CORRECT)
- Write the string “r” to the “ip_addresses.txt” file
- Store the file object in the file variable while inside the with statement (CORRECT)
Thus line of code, open(“ip_addresses.txt”, “r”) as file: is used in Python to open the file “ip_addresses.txt” in read mode (“r”) and to store the obtained file object in the variable file inside the with statement, ensuring that the file is properly closed once the code is executed, even if an error occurs while the file is being handled.
TEST YOUR KNOWLEDGE: WORK WITH FILES IN PYTHON
1. 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?
- with open(“logs.txt”, “r”) as file: (CORRECT)
- with open(“r”, “logs.txt”) as file:
- file = open(“logs.txt”, “r”):
- with file.open(“logs.txt”, “r”):
The correct line of code for opening and reading from the ‘logs.txt’ file is given below: open(“logs.txt”, “r”). The with keyword ensures that all resources will be released gracefully, thus automatically closing the file after exiting the with statement, even if an exception occurs. The open() function basically takes two string arguments, with “logs.txt” and “r”, which indicates that the file must be opened in read mode. Lastly, the as file part assigns the file object to the variable file for processing that file within the with block.
2. 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?
- login_attempts = login_file.read() (CORRECT)
- login_file.read() as login_attempts
- login_attempts = read(login_file)
- login_attempts = login_file.reader()
The program reads all the contents of the log file and stores the same into a variable login_attempts through the command login_attempts=login_file.read(). The attribute .read() reads the whole file as one big string. The above code now assigns this value to the variable login_attempts allowing you to work with that file’s content as text.
3. 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?
- split(file, ip_addresses)
- ip_addresses = file.split() (CORRECT)
- ip_addresses.split(file)
- ip_addresses = split(file)
The ip_addresses = file.split() statement breaks apart the individual IP addresses within the file variable and saves them as a list into a variable known as ip_addresses. The method .split() delimits a string into a list by defining the boundaries that separate list members. When no arguments are given as a delimiter, the method uses any whitespace characters, spaces, tabs, and newlines as its delimiter. This proves to be useful when content has to be divided into manageable sections for further analysis.
4. 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.
- An if statement that checks if the login timestamp occurred at unusual hours (CORRECT)
- A counter variable that keeps track of the number of failed login attempts
- A for loop that iterates through the list of timestamps (CORRECT)
- An if statement that checks if a specific user has multiple login timestamps during unusual hours
The code should include a for loop that iterates through the list of timestamps and an if statement that checks if the login timestamp occurred at unusual hours.
TEST YOUR KNOWLEDGE: DEBUG PYTHON CODE
1. What types of errors might you encounter while debugging code? Select three answers.
- Iteratives
- Logic errors (CORRECT)
- Exceptions (CORRECT)
- Syntax errors (CORRECT)
While debugging, we often come across three typical problems, namely syntax error, logic error, and exception. According to Python, it happens when one uses the language incorrectly against its rules; it then puts forth syntax error. While the logic error does not generate any error messages, it, however, results in some incorrect or unintended outcomes. The third type of error is an exception that arises when the code is syntactically correct but the program comes across an unhandled condition during execution.
2. 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.)


Based on what you discover, how can you fix the error?
- Change the keyword elsif to elif. (CORRECT)
- Indent the elsif statement.
- Remove all colons (:).
- Use single equals signs (=) and not double equals signs (==).
On executing this code, the error message will state the specific details of the syntax error along with the mention of the line number where the error has occurred. The resolution of this issue involves replacing the incorrect keyword elseif by the proper python keyword elif. As a whole, it can be understood that a syntax error occurs when someone improperly utilizes the python language; for example, when one misspells a keyword. Well, if the condition operates system == “OS 2,” then the correct keyword required is elif before that condition.
3. 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?
- Name error
- Syntax error
- Logic error (CORRECT)
- Exception
A logic error is this. When reasoning within the code does not correspond to the intent of the programmer, this results in what is known as an unintended outcome. In this case, the unintended outcome is a security incident ticket being sent to the wrong team-an error in the logic of the program itself.
4. 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?
- Exception (CORRECT)
- Logic error
- Syntax error
- Iterative
This is an example of an exception. Exception occurs in python when the situation happens that the code is syntactically correct but Python can do nothing about it as it occupies an index that does not exist in the sequence.
5. Which of the following are syntax errors? Select two answers.
- Typing < in a condition when <= is needed
- Calling a function that has not been defined
- Omitting the colon at the end of an iterative statement header (CORRECT)
- Misspelling the Python keyword elif by typing elsif instead (CORRECT)
For example, maybe missing a colon at the end of a loop statement header, or spelling the keyword elif as elsif. These errors relate to syntax misuses in the language – any wrongful usage in Python will break its syntax rules.
MODULE 4 CHALLENGE
1. What are the three types of errors you will encounter while debugging?
- Syntax errors, exceptions, and comment errors
- Exceptions, logic errors, iterative errors
- Syntax errors, logic errors, and exceptions (CORRECT)
- Logic errors, comment errors, and iterative errors
2. The purpose of the following code is to print the characters in a device ID. 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.)

What is the error related to?

- A misspelled variable
- A missing colon (:)
- A missing quotation mark (“) (CORRECT)
- A missing double equals sign (==)
3. The purpose of this code is to greet a user by their first name when they log in. 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.)

How can you fix this error?

- Indent the line that assigns a value of “Charley” to the first_name variable
- Use “name” instead of “first_name” when calling welcome_user()
- Remove the quotation marks surrounding the argument “first_name” when calling welcome_user() (CORRECT)
- Call welcome_user() before the function definition
4. Why might you use print statements when debugging code?
- To prevent errors from occurring
- To create error messages
- To identify which sections of the code are working properly (CORRECT)
- To add missing syntax to the code
5. If you want to read a file called “logs.txt”, which line of code allows you to open this file for purposes of reading it and store it in a variable called file?
- with open(file, “r”) as logs.txt:
- with open(“logs.txt”, “r”) as file: (CORRECT)
- with file.open(“logs.txt”, “r”):
- with open(“logs.txt”, file, “r”):
6. What does the following code do?
logins = "pwashing jhill tshah"
usernames = logins.split()
- Removes the last username in the logins variable and stores the string in the usernames variable
- Removes the blank spaces that split the usernames in the variable logins and stores the string in the variable usernames
- Splits a string variable called logins into single characters
- Splits a string variable called logins into a list of strings and stores it in the variable usernames (CORRECT)
7. What is the process of converting data into a more readable format?
- Slicing
- Debugging
- Splitting
- Parsing (CORRECT)
8. What does the following code do?
read_text = text.read()
- Reads the string text and stores it the file read_text
- Replaces the contents of the file read_text with the contents of the file text
- Reads the text variable, which contains a file, and stores it as a string in read_text (CORRECT)
- Splits the text variable, which contains a string, and stores it as a list in read_text
9. You want to check for unusual login activity. Specifically, you want to read a log file that contains information on each login attempt, including whether it failed or was successful. You should then parse the data into a logins list, and then you should separate all failed log entries into a separate failed_logins list. If you want to automate this through Python, what would be part of your code? Select three answers.
- A for loop to iterate through all items in the logins list (CORRECT)
- A split() function to split the login information into a list (CORRECT)
- An if statement to check if a login attempt failed (CORRECT)
- A counter variable to keep track of the number of failed logins
10. 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.)

How can you fix the error?

- Add a missing colon (:) (CORRECT)
- Remove the quotation marks around number
- Change indentation
- Spell a variable correctly
11. 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.)

11. 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.)

- Change “user3” to “user1” in the conditional.
- Change the != operator to the == operator in the conditional. (CORRECT)
- Change “user3” to “user2” in the conditional.
- Change the indentation so that the line that prints the warning is not indented.
12. When debugging code, what are effective ways to determine which sections of code are working properly? Select all that apply.
- Use a debugger (CORRECT)
- Add print statements (CORRECT)
- Delete blank lines from the code
- Add comments in the code
13. What does the following code do?
with open("logs.txt", "r") as file:
- It opens a file called “logs.txt” in write mode and stores it in a variable called file.
- It opens a file called “logs.txt” in read mode and stores it in a variable called file. (CORRECT)
- It copies a file called “r” into a new file “logs.txt”.
- It copies a file called “logs.txt” into a new file “r”.
14. You’ve read a log file into the variable file_text. The file_text variable contains a string of 50 usernames of employees at your company. In order to pass it into a function that checks the login count of each user, the string should be divided into a list of separate usernames. How do you convert this string into a list and store it in a variable usernames?
- usernames = split(usernames, file_text)
- usernames = file_text.split() (CORRECT)
- usernames = usernames.split(file_text)
- file_text.split() as usernames
15. After you’ve opened a log file as file, which line of code will help you read the file into a variable called text?
- text = read(file)
- text = read(file, “r”)
- text.read(file)
- text = file.read() (CORRECT)
16. 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.
- An if statement that checks if there were more than three failed login attempts (CORRECT)
- A counter variable that increments when a failed login is detected (CORRECT)
- A for loop that iterates through the list of logins (CORRECT)
- A line of code that reassigns a counter variable to 0 if there is a failed login attempt
17. What is debugging?
- The practice of identifying and fixing errors in code. (CORRECT)
- The practice of calling a function from multiple places in a larger program
- The practice of improving code readability.
- The practice of improving code efficiency.
18. You did not define a function before calling it. What type of error is this?
- Index out of bounds
- Syntax error
- Logic error
- Exception (CORRECT)
19. 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?
- device_ids = split(device_ids, logins)
- device_ids = logins.split() (CORRECT)
- logins.split() as device_ids
- device_ids = device_ids.split(logins)
20. 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 _____.
- slicing
- dividing
- parsing (CORRECT)
- debugging
21. What does the following code do?
new_format = old_format.read()
- Inserts the string stored in the new_format variable into the file stored in the old_format variable
- Reads the old_format variable, which contains a file, and stores it as a string in new_format (CORRECT)
- Prints the contents of old_format
- Detects certain text patterns in old_format
22. The purpose of the following code is to search a list. 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.)

What is the error related to?

- A missing colon (:) (CORRECT)
- A missing comma (,)
- A missing quotation mark (“)
- A misspelled variable
23. 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.
- “access.txt” (CORRECT)
- read()
- “r” (CORRECT)
- open() (CORRECT)
24. You included username_list[10] in your code, but username_list only contains five elements. What type of error is this?
- Name error
- Exception (CORRECT)
- Syntax error
- Logic error
25. If you know there is a logic error somewhere inside a function, how can you figure out the exact location?
- Delete the function from the program
- Move the function to another location
- Place print statements in and around the function (CORRECT)
- Write comments in and around the function
26. You want to check if a device is running a particular operating system that needs updates. Devices that contain a substring of “i71” in their device ID are running this operating system. First, you want to read in a log file that contains the device ID for all devices and convert it into a string. You should then parse this string into a devices list. Then, you should separate all device IDs that contain the substring “i71” into a separate list called updates_list. If you want to automate this through Python, what would be part of your code? Select three answers.
- A counter variable to keep track of the number of devices containing the substring “i71”
- A split() function to split the string containing the information in the log file into a devices list (CORRECT)
- An if statement that checks if elements in devices contain the substring “i71” (CORRECT)
- A for loop to iterate through all items in the devices list (CORRECT)
27. You did not assign a value to a variable before using it in a conditional statement. What type of error is this?
- Exception (CORRECT)
- Syntax error
- Index out of bounds
- Logic error
28. What is parsing?
- The process of reading data line by line
- The process of writing data to a new file
- The process of converting data into a more readable format (CORRECT)
- The process of copying data to other files
CONCLUSION – Python in Practice
Thus, this module placed participants in a practical way at the historical hands-on experience with Python application for cybersecurity. These exercises have led delegates to sharpen their practical application of file-handling and automation in the efforts to yield better results for performance optimization in cybersecurity workflow.
While debugging strategy involvement assures the learner of having the skills to enable them to troubleshoot and improve upon their code, it also builds a strong foundation for tackling the world of scripting challenges in a real-world scenario of cybersecurity. Such a complete module is definitely a reference to be availed to those in quest of bridging the gap between theoretical understanding and its practical application in the evolving domain of security automation using Python.