Picking up Python

The journey so far:

This has been a long time coming. When I first got into cybersecurity, I remember a line from a blog about how developers become gods as they move into cybersecurity due to their coding capabilities.

Unfortunately, I started but did not keep up with my learning of python. I could manipulate some python scripts on a very basic level when I tinkered with pentesting, but I could not write code from scratch.

However I realized that I would need to get comfortable with C and Assembly as I started my foray into malware analysis. Cue me starting with C on W3 Schools and reading K. N. King's C Programming book. This was quickly followed by me asking my mom if I ever had a helmet when I was younger.

A few Google searches and blunt forum posts later, I realized the folly of my ways and traded #include <stdio.h> for printf("hello world").

This is where it gets controversial. I studied W3's Python Tutorial, but struggled to understand how these would apply in actual scripts. So I took a different approach, and decided on a more hands on approach by using Gemini's Guided Learning mode to learn.

Disclaimer: I want to stress that I'm not getting GenAI to write code which I pass off as my own, but using it to write a script which I then analyze and ask questions about till I can write my own script from scratch while understanding why I'm writing each line.

Using Gemini's Guided Learning:

In this section, I'm going to summarize how I used Gemini to teach me to write my first script. As I used multiple chat windows over many days for all of this, I'll stich and skip certain sections for brevity and coherence, but the objectives of this section is two fold: (i) prove that I used Gemini to learn and not pass off code as my own (ii) demonstrate to others that this is (in my very nascent opinion at least) that this is a viable method to learn.

Maybe I'll look back in a few years and update that this was a bad idea, who knows. Follow me for more questionable life choices.

Figuring out which project I'd like to try:

I start off by asking for a list of cyber related projects for n00bs. From the given list, I narrowed it down to a super simple log parser that reads logs and provides the IPs which have the word "FAILED" in it. Foreshadowing much.

I then ask it to write me the python script:

Here's the code it provided:

import re

def parse_log_file(filename="log.txt"):
    """
    Parses a log file to find IP addresses from lines containing "FAILED".

    Args:
        filename (str): The path to the log file to be parsed.

    Returns:
        list: A list of unique IP addresses found in the failed login attempts.
    """
    # Using a set to automatically handle duplicates
    failed_ips = set()
    
    # A common regular expression for finding IPv4 addresses
    ip_pattern = r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b"

    try:
        # 'with open' ensures the file is properly closed even if errors occur
        with open(filename, 'r') as log_file:
            # Read the file line by line
            for line in log_file:
                # Check if the keyword "FAILED" is in the current line
                if "FAILED" in line:
                    # Use the regular expression to find the IP address in the line
                    match = re.search(ip_pattern, line)
                    if match:
                        # If an IP is found, add it to our set
                        failed_ips.add(match.group(0))
    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found.")
        return []
    except Exception as e:
        print(f"An error occurred: {e}")
        return []

    # Return the findings as a list
    return list(failed_ips)

# --- How to use the script ---

# 1. Create a sample log file named 'log.txt' with the following content:
#    (You can copy and paste this into a new text file)
"""
INFO: Successful login for user 'alice' from 192.168.1.50
WARNING: FAILED login attempt for user 'root' from 10.0.0.101
INFO: File access by user 'bob' from 192.168.1.55
WARNING: FAILED password for user 'admin' from 172.16.31.4
ERROR: Service unavailable
WARNING: FAILED login attempt for user 'guest' from 10.0.0.101
"""

# 2. Run the script. It will read 'log.txt' and execute the function.
if __name__ == "__main__":
    # Name of the log file to parse
    log_filename = "log.txt"
    
    # Call the function and get the list of IPs
    extracted_ips = parse_log_file(log_filename)
    
    # Print the results
    if extracted_ips:
        print(f"Found IP addresses from failed attempts in '{log_filename}':")
        for ip in extracted_ips:
            print(ip)
    else:
        print("No IPs from failed attempts were found.")

Making heads or tails of the code

Last updated

Was this helpful?