COURSE 7 – AUTOMATE CYBERSECURITY TASKS WITH PYTHON

Module 4: Python in Practice  

GOOGLE ADVANCED DATA ANALYTICS PROFESSIONAL CERTIFICATE

Complete Coursera Study Guide

INTRODUCTION – Python in Practice

Throughout this section, participants will delve into the practical application of Python in the context of cybersecurity, emphasizing the automation of essential tasks related to file handling. The module commences with an exploration of opening and reading files, providing participants with a foundational understanding of handling diverse file formats. Moving forward, the focus shifts to parsing files and structuring their contents, enabling participants to extract meaningful insights from various data sources efficiently.

An integral aspect of this module is the emphasis on debugging code, equipping participants with strategies to identify and rectify errors in their Python programs. This hands-on approach not only solidifies participants’ proficiency in Python but also hones their problem-solving skills in the realm of cybersecurity automation. As participants progress through this comprehensive overview, they will gain practical insights into leveraging Python for file manipulation and automation, setting the stage for proficient and effective cybersecurity scripting.

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.

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)

Using automated Python programs, you can track whether several failed login attempts occurred within a short span of time, whether login attempts occurred outside of normal work hours, and whether login attempts occurred from IP addresses that are not established work zones. In all of these cases, you can obtain the data needed for Python automation.

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

Python for loops contribute to automation by allowing you to perform the same action a certain number of times based on a sequence.

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 work with files is important for automation because cybersecurity-related information is often found in log files.

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

  • .txt (CORRECT)
  • .csv (CORRECT)
  • .jpeg
  • .gif

Common file formats for security logs include .txt and .csv. Both file formats are types of text files, meaning they only contain plain text. It is easy to extract data from .txt and .csv files.

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)

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.

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 code with open(“logs.txt”, “r”) as file: is the correct line of code to do this. The with keyword ensures all resources are released while opening and reading the file. This includes ensuring the file is closed after exiting the with statement. Then, calling the open() function with the file “logs.txt” and “r” as arguments indicates to read the “logs.txt” file. Finally, as file specifies to store the file object in the variable file.

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 code login_attempts = login_file.read() reads the log file and stores it in a variable called login_attempts. The .read() method converts files into strings. The code assigns the string it creates to another variable named login_attempts.

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 code ip_addresses = file.split() separates the individual IP addresses in the file variable and then stores this as a list in a variable called ip_addresses. The .split() method converts a string into a list. It separates the string based on a character passed into the function as an argument. If a character is not passed in, it will separate the string whenever it encounters a whitespace.

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)

Syntax errors, logic errors, and exceptions are all types of errors you might encounter while debugging code. Syntax errors involve invalid usage of the Python language. Logic errors may not cause error messages, but they produce unintended results. Exceptions happen when the program does not know how to execute code even though it is syntactically correct.

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

Cybersecurity - Course 7 - elsif to elif - Question
Coursera img
Cybersecurity - Course 7 - elsif to elif - Answer
Coursera img

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 (==).

When you run this code, the error message can help you identify the syntax error and the line number where it occurs. Changing the keyword elsif to elif will fix the error. Syntax errors involve invalid usage of the Python language, such as misspelling a keyword. The correct spelling for the keyword needed before the condition operating_system == “OS 2” is elif.

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

This is a logic error. Logic errors are errors that result when the logic used in code produces unintended results. In this situation, because the security incident ticket is forwarded to the wrong team, there is an unintended result.

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 exception. Exceptions occur when Python does not know how to execute code even though it is syntactically correct. This happens if you ask Python to access an index that does not exist.

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)

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.

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

print the characters in a device ID - Cybersecurity - Course 7 - Question
Coursera img

What is the error related to?

print the characters in a device ID - Cybersecurity - Course 7 - Answer
Coursera img
  • 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.)

greet a user by their first name when they log in - Cybersecurity - Course 7 - Question
Coursera img

How can you fix this error?

greet a user by their first name when they log in - Cybersecurity - Course 7 - Answer
Coursera img
  • 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”):

5. Questions

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

print the numbers from 0 to 9 - Cybersecurity - Course 7 - Question
Coursera img

How can you fix the error?

print the numbers from 0 to 9 - Cybersecurity - Course 7 - Answer
Coursera img
  • 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.)

print a warning message if it finds "user3" in the list - Question
Coursera img

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

print a warning message if it finds "user3" in the list - Answer
Coursera img
  • 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.)

purpose of the following code is to search a list - Cybersecurity - Coursera Answer
Coursera img

What is the error related to?

20
Coursera img
  • 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

In conclusion, this module has provided participants with a practical and hands-on exploration of Python’s application in the field of cybersecurity. By focusing on tasks related to file handling and automation, participants have not only honed their Python programming skills but also gained valuable insights into streamlining and optimizing cybersecurity processes.

The emphasis on debugging strategies ensures that participants are well-equipped to troubleshoot and refine their code, fostering a robust foundation for scripting tasks in real-world cybersecurity scenarios. Overall, this comprehensive module serves as a pivotal resource for individuals seeking to bridge the gap between theoretical knowledge and practical application in the dynamic landscape of cybersecurity automation with Python.