This is the seventh course of the Google Cybersecurity Certificate Course on Coursera. Again it’s a mix of my notes and definitions from the course.

Here is a link to my main page for the course.

Course 7 Overview

  • Basic programming concepts in Python
  • Writing effective Python code
  • Working with strings and lists
  • Putting Python into practice

Module 1: Introduction to Python

  • Best for automating short, simple tasks, e.g., sort through event logs
  • Resembles human language
  • Less code
  • Easy to read
  • Standard guidelines
  • Online support
  • Built-in code

Examples of how Python is used in cybersecurity

  • Log analysis
  • Malware analysis
  • Access control list management
  • Intrusion detection
  • Compliance checks
  • Network scanning

Create a basic Python script

  • Good to start with a # comment
print("Hello World")

Data types in Python

  • String data - letters, symbols, spaces. Can’t be used for calculations.
  • Float data - numbers with a decimal point.
  • Integer data - numbers without decimal points.
  • Boolean
  • Lists
# Calculate numbers with print
print(1+1)

Work with variables in Python

  • A container that stores data
  • Creating one is often called assignment
  • Using them is called ‘calling’ them
  • Often used to simplify or clean code, or to use long strings without having to type them all out
  • Important to keep track of data types

Conditional statements in Python

  • Automation is done with conditional statements
  • Starts with if
# Create a conditional

operating_system = "OS 3"
if operating_system == "OS 2":
    print("Updates needed")
else:
    print("No updates needed")

For loops

  • An iterative statement
for i in [1,2,3,4]:
    print(i)

range(0,10)

While loops

# Create a while loop

max_devices = 5
i = 1

while i < max_devices:
    print("User can still connect to additional devices")
    i = i + 1
print("User has reached maximum number of connected devices")

Analysts need to be familiar with iterative statements like for, while, etc.

Module 2: Write effective Python code

  • Functions
  • Modules and libraries
  • Core readability

Functions

  • Like a dishwasher. Helps with automation.

Create a basic function

# Define a function
def greet_employee():
    print("Welcome! You're logged in!")

# Call a function
greet_employee()

Use parameters in functions

# Greet employees by name
def greet_employee(name):
    print("Welcome! You're logged in", name)

greet_employee("Charley Patel")

Return statements

# Return information from a function
def calculate_fails(total_attempts, failed_attempts):
    fail_percentage = failed_attempts / total_attempts
    return fail_percentage

calculate_fails(4,2)

A parameter is an object that is included in a function definition for use in that function, an argument is the data brought into a function when it is called, and the return keyword is used to return information from a function. Additionally, global variables are variables accessible throughout the program, and local variables are parameters and variables assigned within a function that aren’t usable outside of a function.

Explore built-in functions

  • print()
  • type()
  • print(type(“Hello”))
    • Inner function is processed first
  • max()
  • sorted()
# Explore input and output of print
print("This is a string, but", 75, "is a number")
# Explore input and output of type
print(type("security"))
print(type(73.2))
# Explore max
a = 3
b = 6
c = 9
print(max(a,b,c,))
# Explore sorted
username = ["elarson", "bmoreno"]
print(sorted(usernames))

Can import a library, that’s usually made up of modules.

Python Standard Library. An extensive library.

  • re module, good for searching for patterns
  • csv module
  • glob
  • os
  • time

To import a library, just use the import keyword.

Useful external libraries for cybersecurity: numpy and bs4.

Code readability

  • Style guides
  • PEP 8 style guide
    • Python Enhancement Proposals
    • Help with consistency

Module 3: Work with strings and lists

  • Working with strings and lists
  • Writing algorithms
  • Using regular expressions

String operations

  • In between quotation marks
  • str()
# Convert an integer into a string
new_string = str(123)
print(type(new_string))

len returns the number of elements in an object

# Print the length of a string "Hello"
print(len("Hello!"))

.upper() and lower

# Apply upper method to "Hello"
print("Hello".upper())

String indices and slices

# Extract a slice from a string
print("HELLO" [1:4])

E.g. what does the code `print(“HELLO”[2:4]) output? “LL” because slice starts at the character at index 2 and ends one character before index 4.

.index()

# Use the index string method
print("HELLO".index("E"))

Note strings are immutable.

List operations in Python

# Use the insert method
my_list = ["a", "b", "c", "d", "e"]
my_list.insert(1,7)
print(my_list)
# Use the remove method
my_list = ["a", "b", "c", "d", "e"]
my_list.remove("d")
print(my_list)

*Write a simple algorithm

  1. Use string slicing to extract the first three digits from one IP address
  2. Use a loop to apply that solution to every IP address on the list
address = "198.233.xx.xx"

# Extract the first three characters of an IP address
print(address[0:3])
IP = ["198.223.xx.xx", "198.101.xx.xx", "180.064.xx.xx", "192.168.xx.xx", "184.090.xx.xx"]

# Extract the first three characters from a list of IP addresses
networks = []
for address in IP:
    networks.append(address[0:3])
print(networks)

Regular expressions in Python import re

  • Search for any kind of pattern

Q Which string matches with the regular expression “b\wa+b”?

A The string “bkaab” matches with the regular expression “b\wa+b”. The first character must be “b”. After this, the symbol \w is used to match any alphanumeric character, including “k”. Next, the + symbol specifies that there should be one or more occurrences of the character it follows, which in this case is “a”. Finally, the string must end with “b”.

Search for an email with a regex: \w+@\w+\.\w+

  • Strings and lists
  • Writing algorithms
  • Using regular expressions

Module 4: Python in practice

  • Mainly to automate log tasks
  • Opening and reading files
  • Parsing files
  • Debugging code

Automate cybersecurity tasks with Python

  • for loops
  • .txt and csv files

Access a file in Python

with open("login_attempts.txt", "r") as file:
    file_text = file.read()
print(file_text)

Parse a text file in Python

  • The process of converting data into a more readable format
# Assign `import_file` to the name of the text file that contains the security log file

import_file = "data/login.txt"

# First line of the `with` statement
# Use `open()` to import security log file and store it as a string

with open(import_file, "r") as file:
# Assign `import_file` to the name of the text file that contains the security log file

import_file = "data/login.txt"

# The`with` statement
# Use `open()` to import security log file and store it as a string

with open(import_file, "r") as file:

  # Use `.read()` to read the imported file and store the result in a variable named `text`

  text = file.read()

# Display the contents of `text`

print(text)
# Assign `import_file` to the name of the text file that contains the security log file

import_file = "data/login.txt"

# The`with` statement
# Use `open()` to import security log file and store it as a string

with open(import_file, "r") as file:

  # Use `.read()` to read the imported file and store the result in a variable named `text`

  text = file.read()

# Display the contents of `text` split into separate lines 

print(text.split())
# Assign `import_file` to the name of the text file that contains the security log file

import_file = "data/login.txt"

# Assign `missing entry` to a log that was not recorded in the log file

missing_entry = "jrafael,192.168.243.140,4:56:27,2022-05-09"

# Use `open()` to import security log file and store it as a string
# Pass in "a" as the second parameter to indicate that the file is being opened for appending purposes

with open(import_file, "a") as file:

    # Use `.write()` to append `missing_entry` to the log file

    file.write(missing_entry)

# Use `open()` with the parameter "r" to open the security log file for reading purposes

with open(import_file, "r") as file:

    # Use `.read()` to read in the contents of the log file and store in a variable named `text`

    text = file.read()

# Display the contents of `text`

print(text)
# Assign `import_file` to the name of the text file that you want to create

import_file = "data/allow_list.txt"

# Assign `ip_addresses` to a list of IP addresses that are allowed to access the restricted information

ip_addresses = "192.168.218.160 192.168.97.225 192.168.145.158 192.168.108.13 192.168.60.153 192.168.96.200 192.168.247.153 192.168.3.252 192.168.116.187 192.168.15.110 192.168.39.246"

# Display `import_file`

print(import_file)

# Display `ip_addresses`

print(ip_addresses)
# Assign `import_file` to the name of the text file that you want to create

import_file = "data/allow_list.txt"

# Assign `ip_addresses` to a list of IP addresses that are allowed to access the restricted information

ip_addresses = "192.168.218.160 192.168.97.225 192.168.145.158 192.168.108.13 192.168.60.153 192.168.96.200 192.168.247.153 192.168.3.252 192.168.116.187 192.168.15.110 192.168.39.246"

# Create a `with` statement to write to the text file 

with open(import_file, "w") as file:

  # Write `ip_addresses` to the text file

  file.write(ip_addresses)
# Assign `import_file` to the name of the text file that you want to create

import_file = "data/allow_list.txt"

# Assign `ip_addresses` to a list of IP addresses that are allowed to access the restricted information

ip_addresses = "192.168.218.160 192.168.97.225 192.168.145.158 192.168.108.13 192.168.60.153 192.168.96.200 192.168.247.153 192.168.3.252 192.168.116.187 192.168.15.110 192.168.39.246"

# Create a `with` statement to write to the text file 

with open(import_file, "w") as file:

    # Write `ip_addresses` to the text file

    file.write(ip_addresses)

# Create a `with` statement to read in the text file 

with open(import_file, "r") as file:

    # Read the file and store the result in a variable named `text`

    text = file.read()

# Display the contents of `text`

print(text)

Develop a parsing algorithm in Python

# Open, read, and split a text file
with open("login_attempts.txt", "r") as file:
    file_text = file.read()
usernames = file_text.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(usernames, "elarson")

Main takeaways

  • Python has functions and syntax that help you import and parse text files.
    • The with statement allows you to efficiently handle files.
    • The open() function allows you to import or open a file. It takes in the name of the file as the first parameter and a string that indicates the purpose of opening the file as the second parameter.
      • Specify "r" as the second parameter if you’re opening the file for reading purposes.
      • Specify "w" as the second parameter if you’re opening the file for writing purposes.
    • The .read() method allows you to read in a file.
    • The .write() method allows you to append or write to a file.
  • You can use a for loop to iterate over a list.
  • You can use an if statement to check if a given value is in a list and execute a specific action if so.
  • You can use the .split() method to convert a string to a list.
  • You can use Python to compare contents of a text file against elements of a list.
  • Algorithms can be incorporated into functions. When defining a function, you must specify the parameters it takes in and the actions it should execute.
# Define a function named `update_file` that takes in two parameters: `import_file` and `remove_list`
# and combines the steps you've written in this lab leading up to this

def update_file(import_file, remove_list):

  # Build `with` statement to read in the initial contents of the file

  with open(import_file, "r") as file:

    # Use `.read()` to read the imported file and store it in a variable named `ip_addresses`

    ip_addresses = file.read()

  # Use `.split()` to convert `ip_addresses` from a string to a list

  ip_addresses = ip_addresses.split()

  # Build iterative statement
  # Name loop variable `element`
  # Loop through `ip_addresses`

  for element in ip_addresses:
    
    # Build conditional statement
    # If current element is in `remove_list`,
    
    if element in remove_list:

      # then current element should be removed from `ip_addresses`

      ip_addresses.remove(element)

  # Convert `ip_addresses` back to a string so that it can be written into the text file     

  ip_addresses = " ".join(ip_addresses)

  # Build `with` statement to rewrite the original file

  with open(import_file, "w") as file:

    # Rewrite the file, replacing its contents with `ip_addresses`

    file.write(ip_addresses)

# Call `update_file()` and pass in "allow_list.txt" and a list of IP addresses to be removed

update_file("allow_list.txt", ["192.168.25.60", "192.168.140.81", "192.168.203.198"])

# Build `with` statement to read in the updated file

with open("allow_list.txt", "r") as file:

  # Read in the updated file and store the contents in `text`

  text = file.read()

# Display the contents of `text`

print(text)

Debugging strategies

  • Syntax errors
  • Logic errors
    • Use print statements to try to identify them
  • Exceptions

Even the best software engineers have errors. It’s a learning opportunity.

Apply debugging strategies

  • Need to know the purpose of the code
  • Debuggers
  • Use print statements

Resources