
Running Your First Python Script. Every security tool in this course begins in the same place: a Python file that you write, save and run. This lecture takes you through that process slowly, so that you feel comfortable before the real work begins.
We start by checking that Python 3 is installed and that your terminal can find it. You will open a code editor, create a project folder for the course and make a new file with a .py ending. Then you will write your first line of code, a call to print that shows a short message such as a security tool starting up. We explain what print does, why the text sits inside quotation marks and what the parentheses mean.
You will learn how to run the file from the terminal and what happens when you do. Python reads your file from top to bottom and carries out each line in order. We look at the difference between running a file and typing commands interactively, and we explain when each is useful.
We also cover the mistakes that nearly every beginner makes. A missing quotation mark, a misspelled command and a file saved in the wrong folder all produce error messages, and we read some of them together so that errors stop looking frightening. Reading an error from the bottom up is a habit that will serve you throughout the course.
We finish by adding comments, which are notes for human readers, and by keeping your files tidy.
By the end of this lecture you will be able to write, save and run a Python script and read a simple error message.
Storing Security Details in Variables. Security work involves a great deal of small facts: a username, a port number, an address, a count of failed attempts. A variable gives each fact a name, so that your program can store it and use it later. This lecture introduces variables using exactly these kinds of details.
You will learn how to create a variable by choosing a name and assigning a value with the equals sign. We discuss good names, such as failed_attempts or server_name, and why clear names make a script easier to read and to review. We also cover the naming rules Python enforces, including that names cannot begin with a digit or contain spaces.
We introduce the basic types of data. Text is stored as a string, whole numbers as integers, numbers with decimals as floats and true or false answers as booleans. You will see how to check the type of a value, and why it matters: the text 22 and the number 22 behave differently, and mixing them up is a frequent source of bugs.
We practice changing a variable, using it in simple arithmetic, such as adding to a counter each time something happens, and printing its value. We also discuss that a variable holds a value at a particular moment and can be replaced.
We finish with a small exercise that records the details of an imaginary login attempt and prints a summary of them.
By the end of this lecture you will be able to create variables, choose clear names and recognize the basic data types.
Building Log Messages with f-Strings. Security tools constantly produce messages: a warning that a login failed, a note that a file changed, a line saying a scan has finished. Good messages combine fixed text with changing values, and f-strings are the cleanest way to do that in Python.
We begin with the problem. Joining text and values using plus signs quickly becomes awkward, and it fails when a number is mixed with text. An f-string solves both difficulties. You place the letter f before the opening quotation mark and write variable names inside curly braces, and Python fills in their values for you.
You will build several messages in the style of real log entries. For example, a message may state the user name, the address the attempt came from and how many failures have occurred. We practice including numbers, controlling how many decimal places a float shows and adding a timestamp from a variable.
We discuss what makes a log message useful. It should say what happened, to whom or what, and when, in a consistent format that a person or a program can read later. We compare a vague message with a precise one, and talk about consistency, because tools that parse logs later depend on predictable wording.
We also mention a safety habit: never place passwords or secret keys in log messages.
By the end of this lecture you will be able to build clear, consistent log messages using f-strings.
Cleaning Up Text with String Methods. Real security data is messy. Log lines have stray spaces, usernames arrive in mixed capitals, and a file may contain blank entries. Before any check can be trusted, the text must be tidied. Python's string methods do this work, and this lecture teaches the ones you will use most.
A method is an action attached to a value, written after a dot. We start with strip, which removes spaces and line endings from both ends of a string, a step you will use constantly when reading files. We then use lower and upper to make text uniform, so that Admin, ADMIN and admin are treated as the same user. The replace method swaps one piece of text for another, and we use it to remove unwanted characters.
You will also learn methods that answer questions about text. startswith and endswith check how a string begins or ends, the in keyword tests whether one piece of text appears inside another and find reports where it occurs. We use these to recognize lines containing words such as failed or denied.
We discuss an important point: strings cannot be changed in place, so each method returns a new string that you must store in a variable. Forgetting this is a classic beginner error.
We combine several methods to clean a messy sample log line and compare the before and after.
By the end of this lecture you will be able to tidy and inspect text using the most common string methods.
Checking a Value with if and Comparisons. A security tool must make decisions. Is the number of failed logins too high? Is a port on the approved list? Is a password long enough? The if statement lets a program carry out an action only when a condition is true, and this lecture introduces it.
We begin with comparisons, which produce a true or false answer. You will learn the operators for equal, not equal, greater than, less than and their combined forms, and how to print the result of a comparison to see it. A common beginner mistake is confusing a single equals sign, which assigns a value, with a double equals sign, which compares, and we address it directly.
Next we write the if statement itself. We explain the colon at the end of the line and the indented block beneath it, because Python uses indentation to show which lines belong to the condition. We write a check that prints a warning when a count of failed logins reaches a chosen limit and stays silent otherwise.
You will also learn to combine conditions using and, or and not, for example flagging activity only when the count is high and the time is outside working hours. We discuss readable conditions and the value of giving thresholds a clear name instead of burying a mystery number in the code.
We finish by testing the check with values below, at and above the limit, since edges are where mistakes hide.
By the end of this lecture you will be able to write conditions and use if statements to decide when to act.
Handling Both Outcomes with else and elif. An if statement handles the case where a condition is true, but a security tool usually needs to respond to the other cases as well. A login either succeeded or failed, a count is low, medium or high, and a port is allowed or unexpected. The else and elif keywords let you handle all of these clearly.
We begin with else, which provides the action to take when the if condition is false. We rewrite the failed-login check from the previous lecture so that it prints a warning when the count is high and a reassuring message otherwise. We see that exactly one of the two blocks runs.
Next we introduce elif, short for else if, which lets you test several conditions in order. We use it to classify a count of failed attempts as low, medium or high severity, and we explain that Python checks the conditions from the top and stops at the first one that is true. This means the order matters, and we show what goes wrong when a broad condition is placed before a narrow one.
You will learn how to avoid common mistakes, such as overlapping ranges, gaps that no condition covers and forgetting the final else that catches anything unexpected. We also discuss why a default branch is valuable in security code, because unexpected input should be noticed and not ignored.
We practice by writing a small function-free script that classifies several sample values.
By the end of this lecture you will be able to write decisions that cover every outcome, including unexpected ones.
Storing Many Items in a List. Security work rarely involves a single value. You have a collection of usernames, a set of open ports, a series of log lines or a group of addresses. A list is Python's basic container for such a collection, and this lecture shows you how to create and use one.
We start by writing a list with square brackets and commas, for example a list of server names or ports. You will learn that each item has a position, called an index, which starts at zero, and you will practice reading items by index, including counting from the end with negative numbers. We use len to find how many items a list holds.
You will then learn how to change a list. The append method adds an item to the end, insert places one at a chosen position, remove deletes a particular value and pop removes by position. We discuss that lists keep their order, can hold duplicates and can contain items of different types, though keeping them uniform is usually wise.
We also cover slicing, which extracts part of a list, and the in keyword, which checks whether an item is present, a quick way to ask whether a value appears on a list.
We discuss common errors, such as asking for an index that does not exist, and how to read the message Python gives you.
We finish by building a list of flagged usernames from several sample entries.
By the end of this lecture you will be able to create, read and modify lists confidently.
Repeating Work with a for Loop. Checking one item is easy. Security tools must check hundreds or thousands, and writing the same lines repeatedly is neither practical nor reliable. A for loop repeats a block of code for every item in a collection, and it is probably the most useful tool you will learn in the early part of this course.
We begin with the structure: the word for, a name for the current item, the word in, the collection and a colon, followed by an indented block. You will loop over a list of usernames and print a message for each, and see that the loop name takes each value in turn. We discuss choosing a descriptive loop name, such as user or port.
Next we combine loops with the decisions from earlier lectures. Inside the loop, an if statement can check each item, and we write a script that goes through a list of failed-login counts and prints a warning for each count above a limit. You will also learn to keep a running total or a count of flagged items by creating a variable before the loop and updating it inside.
We cover the range function for repeating something a fixed number of times, and enumerate for numbering items. We also introduce break and continue to leave a loop early or skip an item, and warn against loops that never end.
We finish with a short summary printed after the loop.
By the end of this lecture you will be able to apply a check to every item in a collection.
Storing Security Facts in a Dictionary. A list is excellent for a series of similar items, but a single login attempt has several different facts: who tried, from where, when and with what result. A dictionary stores such related facts together under named keys, and this lecture shows how to use one.
A dictionary is written with curly braces, and each entry pairs a key with a value, such as user with the value alice. You will create a dictionary describing one login attempt and read its parts by key. We discuss why keys make the code self-explanatory compared with remembering that the second item of a list is an address.
You will learn how to add and change entries by assigning to a key, how to remove entries and how to check whether a key exists using in. We explain the difference between reading a key directly, which raises an error when it is missing, and using the get method, which returns a default value instead. This difference matters when data is incomplete, which in security work it often is.
We also look at keys and values that are themselves lists or other dictionaries, so that a record can hold, for instance, a list of recent timestamps. We discuss keeping key names consistent, since a misspelled key creates a silent bug.
We finish by building a dictionary for a server, with its name, address, allowed ports and status, and printing a readable summary.
By the end of this lecture you will be able to store and read related security facts in a dictionary.
Updating and Looping Over Dictionary Data. Once facts are in a dictionary, you will want to change them and process all of them. This lecture covers updating dictionary values and looping through their contents, which is the basis of counting and summarizing in the tools that follow.
We start with updating. You will increase a counter stored in a dictionary each time an event occurs, for example adding one to the failed-login count for a user. We introduce the pattern that makes counting reliable: use get with a default of zero, add one and store the result. This avoids errors when a key appears for the first time, and it is the heart of the counting tools you will build later.
Next we loop. You will learn to loop over the keys, the values and the pairs together using the keys, values and items methods. We write a loop that goes through a dictionary of failed-login counts and prints each user with their count, and another that flags those above a limit.
We discuss sorting. Dictionaries do not sort themselves, but the sorted function can order items by count, which lets you list the most active users or addresses first. We practice showing the top three entries.
We also discuss common mistakes, such as changing a dictionary while looping over it, and how to avoid them by looping over a copy.
We finish by combining everything into a small summary of activity per user.
By the end of this lecture you will be able to update, count and loop through dictionary data.
Lists of Dictionaries: Building a Login Log. A single dictionary describes one event, but a log contains many. Combining the two structures, a list in which every item is a dictionary, gives you a small in-memory table of events that you can search, count and summarize. This lecture builds one in the form of a login log.
We begin by writing a list whose items are dictionaries, each with the same keys: user, address, time and result. You will read a particular event by position and a particular fact inside it by key, for example the address of the third event. We practice adding new events with append, as a real tool would when it reads each line of a file.
Next we loop through the list and apply what you have learned. A for loop visits each event, an if statement picks out the failed ones and a counter or a second list collects them. We write a script that prints every failed login, counts failures per user and builds a separate list of the flagged events.
You will also learn to produce a tidy summary using f-strings, and to sort events by a chosen key using the sorted function with a small key function.
We discuss why consistent keys matter. If one event uses a different spelling, your checks will silently miss it, so we write a short check that confirms each event has the required keys.
We finish by printing a readable table of the log.
By the end of this lecture you will be able to build and analyze a list of dictionary records.
Wrapping Repeated Checks in a Function. By now you may have noticed that the same few lines appear again and again in your scripts. Copying them is error-prone, because a fix in one copy is easily forgotten in the others. A function gives a block of code a name so that you can write it once and use it wherever it is needed. This lecture introduces functions through security checks.
We start with the definition: the def keyword, a name, parentheses holding parameters and an indented body. You will write a function that accepts a count of failed logins and returns whether it exceeds a limit. We explain the difference between printing a value and returning it, since a returned value can be used by other code, tested and combined.
You will learn about parameters and arguments, default values that make a parameter optional and how to call a function with named arguments for clarity. We discuss giving functions names that describe what they do, keeping each one focused on a single task and writing a short comment, called a docstring, that explains its purpose.
We also discuss variable scope, which is the idea that names created inside a function are not visible outside it, and why that is helpful.
We refactor an earlier script so that its repeated checks become function calls, and we test the function with several values, including the boundary.
By the end of this lecture you will be able to write reusable functions that take input and return clear results.
Reading a Log File Line by Line. Logs are the raw material of defensive security. This lecture moves from data typed into your script to data stored in files, which is how real security work happens. You will learn to open a text log and process it one line at a time.
We begin by creating a small sample log file filled with invented entries, including successful and failed logins from fictional addresses. You will learn to open it with the open function and, importantly, to use the with statement, which closes the file automatically even if an error occurs. We explain file modes and why we use read mode for logs, which prevents accidental changes.
Next we read the file. We compare reading everything at once with looping over the file object line by line, and explain why the second approach suits large logs, because it never needs to hold the whole file in memory. Each line arrives with a trailing newline, so we apply the strip method from earlier lectures.
You will learn to handle problems sensibly. A missing file raises an error, so we catch it and print a helpful message that names the path. We also discuss using paths that work no matter where the script is run, and choosing the right text encoding.
We finish by counting the lines and printing the first few, a quick check that the file was read correctly.
By the end of this lecture you will be able to open a log file safely and process it line by line.
Filtering Log Lines for Suspicious Entries. Reading a log is only the first step. Most lines are routine, and the value lies in finding the few that deserve attention. In this lecture you build a filter that picks suspicious lines out of a log using the techniques from earlier lectures.
We start by deciding what suspicious means for our sample data. Examples include lines that mention a failed login, an invalid user or an access denial. We express these as a list of keywords, which keeps the rules in one place and makes them easy to extend. For each line, we convert the text to lowercase and check whether any keyword appears in it.
You will learn to collect the matching lines in a list while keeping their line numbers, using enumerate, so that an analyst can go back to the original log and see the context. We print the results in a consistent format and show a count of how many lines matched out of the total.
We discuss the trade-offs of simple keyword matching. A broad keyword finds more but produces false alarms, while a narrow one may miss events. We talk about the importance of testing the filter on lines that should and should not match, and about reviewing the results by hand.
We also refactor the filter into a function that takes a list of lines and a list of keywords and returns the matches, making it reusable.
By the end of this lecture you will be able to filter a log for suspicious entries and report them clearly.
Counting Failed Logins per User. A single failed login is normal, since people mistype passwords. A user with dozens in a short time may signal a problem. To tell the difference, you need counts, and this lecture builds a tool that counts failed logins for each user.
We combine several earlier ideas. We read the log line by line, select the lines that record a failure and extract the user name from each one. The extraction uses string methods and splitting, which we practice on the exact format of our sample log. We then use a dictionary to count, applying the get pattern that adds one for each failure.
Once the counts are complete, we display them. You will sort the dictionary items from the highest count to the lowest and print a ranked list, and you will show only the users who exceed a chosen threshold. We discuss choosing a threshold sensibly, and the fact that a good value depends on the environment.
You will also learn to handle imperfect data. Some lines may be malformed, have missing fields or contain unexpected capitalization, and a robust tool skips or reports them instead of crashing. We add a counter for skipped lines so that nothing disappears silently.
We finish by turning the logic into a function that returns the dictionary of counts, ready to be reused by later tools.
By the end of this lecture you will be able to count events per user and rank them to find unusual activity.
Writing a Suspicious Activity Report to a File. Findings that exist only on a screen disappear when the terminal closes. Analysts need a record they can save, share and review later. In this lecture you write the results of your log analysis to a report file, which turns a script into a useful tool.
You will learn to open a file for writing and to use the with statement for safe handling. We explain the difference between write mode, which replaces any existing file, and append mode, which adds to the end, and why choosing the wrong one can destroy earlier results. We also look at how to avoid overwriting an important file by checking whether it already exists.
We design the report. A good report begins with a title and the date it was created, summarizes the key numbers, such as total lines read and suspicious lines found, and then lists the findings in a clear format. We build it with f-strings and write each line with a newline at the end.
You will learn to include helpful details, such as the source file name and line numbers, so that a reader can trace each finding back to the original. We discuss keeping the report free of sensitive information, such as passwords, that might appear in raw logs.
We finish by reading the report back to confirm that it contains what we expect, and by organizing the output in a dedicated folder.
By the end of this lecture you will be able to write a clear, traceable report to a file.
Checking Password Length and Character Types. Weak passwords remain one of the most common ways accounts are compromised, so checking them is a classic defensive task. In this lecture you build a checker that examines a password's length and the kinds of characters it contains. You will use only invented sample passwords, never real ones.
We begin with length, using the len function and a minimum chosen by policy. We explain why length matters more than clever substitutions, and how current guidance favors longer phrases over complicated short ones.
Next we classify characters. Python strings offer methods such as isupper, islower, isdigit and isalpha, and we loop through each character to see whether the password includes uppercase letters, lowercase letters, digits and symbols. We use the string module's list of punctuation characters to recognize symbols. Each finding is stored in a boolean variable.
You will combine the results to produce a clear report, such as a list of the policy rules the password failed. We write this as a function that returns both a pass or fail result and the reasons, because a message such as add a digit is far more useful than a bare rejection.
We discuss the limits of such checks. Passing a rule set does not make a password strong, since common words and leaked passwords can satisfy every rule, and we mention password managers and multi-factor authentication as essential partners.
We also stress handling passwords carefully, never printing or logging them.
By the end of this lecture you will be able to check a password against a length and character policy.
Scoring Password Strength. A pass or fail answer is useful, but people often benefit from a graded result that shows how close a password is to being good. In this lecture you extend the checker into a scoring tool that assigns points and converts the total into a strength rating. All examples use invented passwords.
We design the scoring system first. Points are awarded for length, with extra for each step above the minimum, and for each character type present. Points are removed for weaknesses, such as a password made of a single repeated character, one that is purely numeric or one that appears on a short list of very common examples that you include in the script. We keep the rules transparent so that anyone can see why a score was given.
You will learn to translate the total into labels, such as weak, fair, good and strong, using the elif structure from earlier lectures, and to return the label along with a list of suggestions for improvement.
We discuss honesty about what a score means. A simple point system is a teaching tool, not a guarantee, and real-world assessment uses much larger lists of known passwords and checks for patterns. We also discuss avoiding advice that encourages predictable habits.
We test the function with a range of samples, from very poor to very strong, and confirm that the ranking is sensible.
Finally, we refactor the code into small functions, one for each rule.
By the end of this lecture you will be able to build a transparent password scoring tool and explain its limits.
Generating Passwords from a Fixed Pattern. Testing a password checker requires sample passwords, and defensive teams sometimes need to produce consistent, predictable test values. This lecture shows how to generate sample strings from a fixed pattern, and it is explicitly about test data for your own tools. These generated values should never be used as real passwords.
We start with the building blocks. The string module provides ready-made collections of lowercase letters, uppercase letters, digits and punctuation. We write a function that takes a pattern, such as a number of letters followed by digits and a symbol, and builds a string by picking characters in a repeatable way, for example by cycling through the collections using the position as an index. Because the output is deterministic, tests can rely on it.
You will use the generated samples to exercise the checker and scorer from the previous lectures, confirming that a sample built to include every character type passes and that deliberately short or limited ones fail for the expected reasons. This makes the generator a useful testing helper.
We discuss an important distinction. Predictable generation is right for test fixtures, whereas real secrets need unpredictable randomness from a secure source. We introduce the secrets module briefly, explain why the ordinary random module is unsuitable for passwords and point out that passwords from a password manager are the better choice in practice.
By the end of this lecture you will be able to generate repeatable test strings and explain why they must never be used as real credentials.
Hashing Text with hashlib. Hashing is one of the most important ideas in security. A hash function turns any input into a fixed-length fingerprint, and the same input always produces the same fingerprint, while even a tiny change produces a completely different one. In this lecture you use Python's hashlib module to compute SHA-256 hashes of text.
We begin with the concept. A hash is one-way, meaning that you cannot recover the original text from it, and it is designed so that finding two different inputs with the same hash is infeasible. We contrast this with encryption, which can be reversed with a key, and explain why the distinction matters.
You will write code that encodes a string into bytes, a required step because hash functions work on bytes, creates a SHA-256 object and produces its hexadecimal digest. We hash several samples, observe that a single changed letter transforms the result and confirm that identical inputs give identical fingerprints.
We discuss the uses of hashes in defense, including verifying that data has not changed and comparing values without storing them. We also warn about common misconceptions. A plain fast hash alone is not suitable for storing passwords, which require specialized, deliberately slow methods with salts, and older algorithms such as MD5 and SHA-1 are no longer appropriate for security purposes.
We wrap the hashing code in a small function that you will reuse in the next lecture.
By the end of this lecture you will be able to compute and compare SHA-256 hashes and explain what they do and do not provide.
Detecting File Changes with Hashes. File integrity monitoring is a core defensive technique. If you know what a file's fingerprint should be, you can tell at any time whether it has changed, whether through a legitimate update, an accident or an unauthorized modification. In this lecture you build a simple integrity checker using the SHA-256 hashing skills from the previous lecture.
We begin with hashing files instead of text. Files can be large, so we open them in binary mode and read them in chunks, updating the hash as we go. This keeps memory use small and works for files of any size. We wrap the logic in a function that takes a path and returns the hexadecimal digest.
Next we build the baseline. You will create a few sample files in a test folder, compute the hash of each and store the results in a dictionary of file names and hashes, then save it to a JSON file. This baseline represents the known good state.
The checking step recomputes the hashes and compares them with the baseline. The report lists files that are unchanged, files whose hashes differ, files that are missing and new files that were not in the baseline. We then change one sample file deliberately and confirm that the tool notices.
We discuss limitations. The baseline itself must be protected, because an attacker who can alter both a file and its recorded hash defeats the check. We mention storing baselines separately and checking them on a schedule.
By the end of this lecture you will be able to build a file integrity checker that detects changes, deletions and additions.
Spotting Failed Logins in an Auth Log. Authentication logs record who tried to sign in and what happened. This lecture begins our deeper work on log analysis by focusing on the most common finding in them: failed login attempts. We use a sample authentication log with invented users and addresses.
We first study the format. A typical line has a timestamp, a host name, a service name and a message such as a failed password for a user from an address. We read several sample lines and identify the pieces we care about. Understanding the exact format is the foundation of reliable parsing, because a pattern that works on one format will fail quietly on another.
You will write a function that decides whether a line records a failed login. We use the phrases that appear in the sample, handle variations such as an invalid user message and avoid matching successful logins by accident. We test the function with lines that should and should not match, including one with unusual capitalization.
Then we read the whole log, apply the function and collect the matching lines with their line numbers. We print a count, show the first few matches and write the findings to a list that later lectures will reuse.
We discuss why different systems word their messages differently, and how a tool can keep its patterns in one place so that adapting it is easy.
By the end of this lecture you will be able to identify failed login events in an authentication log accurately.
Pulling Fields Out of a Log Line with split. Knowing that a line records a failure is not enough. To count by user or address, you must extract those details from the text. In this lecture you use the split method to break a log line into pieces and select the ones you need.
The split method divides a string at a separator and returns a list of parts. We begin with the default behavior, which splits at spaces and collapses repeated spaces, and apply it to a sample authentication line. You will print the resulting list with index numbers so that the position of each field becomes visible. Then you will pick out the user name and address by index.
Position-based extraction is fragile, because messages vary in length. We therefore introduce a more robust technique: find a known marker word, such as from or for, and take the word that follows it. We write helper functions that return the text after a marker, with a check that the marker exists and a safe result, such as an empty value, when it does not.
You will learn about the maxsplit option, which limits how many splits occur, and the partition method, which splits around the first occurrence of a separator. We also discuss stripping punctuation from the extracted pieces.
We practice by extracting fields from many sample lines and storing each as a dictionary, which creates structured events from raw text.
By the end of this lecture you will be able to turn a text log line into structured fields reliably.
Counting Failed Logins per IP Address. Counting failures by user shows who is being targeted. Counting them by source address shows where the attempts come from, and that is often the more revealing view. In this lecture you build a tool that counts failed logins for each IP address in an authentication log. The addresses are fictional documentation-style examples.
We combine the skills of the previous lectures. The tool reads the log, uses your detection function to find failures and the extraction helpers to obtain the source address, and counts with a dictionary using the get pattern. We handle lines where an address cannot be found by recording them in a separate count, so nothing is silently lost.
Next we rank the results. You will sort addresses by their counts and display the top entries in a clear table, including the share of all failures that each represents. We also build the reverse view, listing for each address the set of users it tried, which uses a set to avoid duplicates. A single address trying many different users tells a different story from one repeating the same user.
We discuss interpreting the numbers carefully. Many users may share an address through a company network, and attackers may spread attempts across addresses, so counts are clues, not verdicts.
We finish by returning the counts from a function so that the next lecture can apply a threshold.
By the end of this lecture you will be able to count and rank failed logins by source address.
Flagging Brute-Force Attempts with a Threshold. A brute-force attack tries many guesses against an account. From a defender's viewpoint, the signature is an unusually high number of failures from one source. In this lecture you turn the counts from the previous lecture into a detection by applying a threshold and producing alerts. The data is a sample log with invented addresses.
We begin by choosing a threshold, for example five failures. We discuss that the right number depends on normal behavior in your environment. Too low a value produces false alarms from forgetful users, and too high a value lets slow attacks through. Making the threshold a named setting at the top of the script makes it easy to review and adjust.
You will write a function that takes the dictionary of counts and the threshold and returns the addresses that meet or exceed it. For each, the tool prints an alert with the address, the count and the users involved. We add a severity label, using the elif structure, so that very high counts are marked more urgent.
We then discuss the limits of simple counting. Time matters, because ten failures in a minute differ from ten failures in a month. We introduce the idea of grouping events by time window and show a simple version that uses the timestamps in the sample log.
We test the detection with a quiet log, a noisy one and an edge case at exactly the threshold.
By the end of this lecture you will be able to detect likely brute-force activity with a threshold and report it clearly.
Detecting Unusual Requests in a Web Server Log. Web servers record every request they receive, and those records often reveal scanning, probing and errors. This lecture applies your log analysis skills to a web server access log, using a sample file with invented clients and paths, in order to detect requests that deserve a closer look.
We begin by studying the common log format, in which each line contains the client address, a timestamp, the request method and path, the response status and the size of the response. You will write a parser that extracts these fields into a dictionary, using split and a few careful string operations, and skips malformed lines while counting them.
Next we define what unusual means from a defender's perspective. We look for a high number of error responses from one client, such as repeated not-found results, which can indicate someone probing for pages that do not exist. We look for requests to sensitive paths, such as administrative pages, that appear on a watch list in your script. We also look at unusual methods and very long request paths, which can indicate malformed or suspicious traffic.
The tool counts these signals per client and lists the clients that cross your thresholds, together with examples of their requests. We discuss false positives, such as a search engine crawler or a broken link, and how an allowlist of known good clients reduces noise.
By the end of this lecture you will be able to parse a web access log and flag unusual request patterns.
Storing Allowed Ports in a Set. Network defense often starts with a simple question: which services should be reachable on a system, and which should not? The approved ports form a policy, and in Python a set is the perfect structure for storing it. This lecture introduces sets through that purpose.
A set is a collection of unique values, written with curly braces. You will create a set of allowed port numbers, such as the ones for web and secure shell access, and see that duplicates disappear automatically. We contrast sets with lists. Sets do not keep a numbered order, but they can answer the question of whether a value is present extremely quickly, and they guarantee uniqueness.
You will learn the essential operations. The add method inserts a value, remove and discard delete one, and the in keyword tests membership. We discuss the difference between remove, which raises an error when the value is missing, and discard, which does not.
We also introduce the set operations that make this structure so useful for security: union combines two sets, intersection finds the values common to both and difference finds the values in one but not the other. We practice each with sample port sets, and explain them in plain language.
We discuss storing the policy clearly, with comments that say why each port is allowed, and keeping it separate from the code that checks it.
By the end of this lecture you will be able to store and query a policy of allowed ports using a set.
Comparing Open Ports Against an Allowed List. Having a policy is only useful if you compare reality against it. In this lecture you take a list of open ports, as it might be reported by a scan of your own system, and check it against the allowed set from the previous lecture. The scan results are sample data supplied in the script, with no scanning involved.
We begin with the data. A scan report for a fictional host lists open ports, and we store it as a list of integers, noting that real reports often contain duplicates and out-of-order values. Converting the list to a set removes duplicates and prepares it for comparison.
The comparison uses set difference. The ports that are open but not allowed are unexpected and deserve investigation, while the ports that are allowed but not open may indicate a service that has stopped. We compute both and print them clearly. You will also use intersection to list the ports that match policy, which is useful for confirming that expected services are running.
We then add context. A small dictionary maps well-known port numbers to the services usually found there, so the report can say, for example, that an unexpected port is commonly used for a database. We discuss that the mapping gives hints, not proof.
We finish by writing the comparison as a function that returns a structured result, and by testing it with several hosts.
By the end of this lecture you will be able to detect unexpected open ports by comparing them with a policy.
Splitting an IP Address into Octets. IP addresses appear in nearly every security log, and defensive tools must be able to examine them. Before you can validate or compare them, you need to understand their structure. In this lecture you break an IPv4 address into its four numbers, called octets, and learn how to work with them.
We begin with the format: four numbers between zero and 255, separated by dots. Using the split method with a dot as the separator, you turn the text into a list of four strings. You will print each piece, convert them to integers with the int function and see what happens when a piece is not numeric, which raises an error that we learn to anticipate.
We discuss why splitting is useful. The first octet or two often identify a network, so you can group addresses by prefix, count how many fall within a range and recognize private address ranges, which are reserved for internal use. We write small functions that report whether an address lies in a private range, using the documented reserved blocks.
You will also learn about the edge cases that cause bugs. Addresses with too few or too many parts, values above 255, leading zeros and stray spaces all appear in messy data, and we show how each behaves.
We finish by writing a function that returns the octets as a list of integers or reports clearly that the input is not an address.
By the end of this lecture you will be able to split and interpret IPv4 addresses in Python.
Validating an IP Address with a Function. Logs and configuration files contain text that is supposed to be an IP address but sometimes is not. A tool that trusts such text can crash or, worse, make wrong decisions. In this lecture you write a validation function that decides reliably whether a string is a valid IPv4 address.
We build it step by step from the previous lecture. The function first strips whitespace, then splits on dots and checks that exactly four parts exist. It confirms that each part contains only digits, converts it and verifies that it lies between zero and 255. It returns true only if every test passes. We write the checks as early returns, which keeps the logic flat and readable.
You will test the function with a thorough set of cases: valid addresses, addresses with a missing part, an extra part, letters, negative signs, empty parts and numbers that are too large. We use a small table of inputs and expected results and loop over it, which is a simple form of automated testing and a habit worth building.
We then compare the hand-written function with the ipaddress module in Python's standard library, which validates addresses and also supports IPv6. We discuss when writing your own is a good learning exercise and when the standard tool is the better choice.
We also discuss using validation at the edges of your tools, so that bad data is rejected before it spreads.
By the end of this lecture you will be able to write and test a function that validates IP addresses.
Checking Scan Results Against an IP Allowlist. An allowlist records the addresses that are expected and approved, and anything outside it deserves a look. In this lecture you check a list of addresses seen in sample scan output or a log against an allowlist, and report the unexpected ones. The addresses are fictional documentation examples.
We begin by storing the allowlist. It may contain individual addresses and entire network ranges, such as an internal subnet. We use the ipaddress module, which makes it straightforward to ask whether an address belongs to a network, and we discuss why this is more reliable than comparing text prefixes.
You will write a function that takes an address and the allowlist and returns whether it is approved, validating the address first and treating invalid input as a finding in its own right. We then loop over the observed addresses and sort them into three groups: approved, unexpected and invalid. Using a set for the observed addresses removes duplicates, and we keep a count of how many times each appeared.
The report lists unexpected addresses with their counts and, where available, the log lines in which they appeared. We discuss triage. An unexpected address is not necessarily hostile, since it may be a new device or a legitimate visitor, and the right response is to investigate and then decide whether to update the allowlist.
We finish by writing the results to a file and by testing the function with boundary cases at the edges of a range.
By the end of this lecture you will be able to compare observed addresses with an allowlist and report the exceptions.
Reading a Web Response: Status Codes and Headers. Web applications reveal a great deal about their security through their responses. This lecture introduces the parts of an HTTP response that defenders inspect, and you learn to read them in Python. To keep the course self-contained and safe, we work with sample response data stored in the script, and you examine only systems that you own or are authorized to test.
We begin with the status code, a three-digit number that summarizes the outcome. You will learn the families: two hundred for success, three hundred for redirection, four hundred for client problems and five hundred for server problems. We write a function that explains a code in plain language and flags those that deserve attention, such as repeated forbidden responses.
Next we meet headers, the named values that accompany a response. We store a sample set as a dictionary and read individual headers by name. We discuss that header names are case-insensitive, so a robust tool normalizes them to lowercase before looking them up. We also look at headers that reveal information, such as the server software and its version, and discuss why exposing such detail can help attackers.
You will learn to loop over all headers and print them neatly, and to handle a missing header gracefully, using the get method.
We also introduce the requests library conceptually and describe how a real check would fetch a response, while keeping our exercises on sample data.
By the end of this lecture you will be able to read status codes and headers and interpret what they mean for security.
Auditing Security Headers. Several HTTP response headers instruct the browser to apply protections, and their absence leaves a site more exposed. Checking for them is a common defensive audit, and in this lecture you automate it. The responses you examine are sample data, and any real check should only be run against sites you own or have permission to assess.
We begin with the headers that matter. Strict-Transport-Security tells browsers to use encrypted connections. Content-Security-Policy restricts where scripts and other content may load from, which reduces the impact of injection flaws. X-Content-Type-Options prevents browsers from guessing content types, and X-Frame-Options or its modern equivalent limits embedding in other pages, protecting against clickjacking. Referrer-Policy and Permissions-Policy control information sharing and browser features.
You will write an audit function that takes a dictionary of response headers and a table of the required headers with a short explanation and a severity for each. The function normalizes names, checks for presence and, for some headers, checks the value for weak settings. It returns a list of findings.
We then produce a readable report with a score, such as the number of required headers present, and recommendations for each gap. We test it with a well-configured sample, a poorly configured one and one with a weak value.
We discuss that headers are one layer of defense, not a complete solution.
By the end of this lecture you will be able to audit a response for missing or weak security headers.
Checking Certificate Expiry with Dates. An expired certificate breaks secure connections, causes outages and trains users to ignore browser warnings. Monitoring expiry dates is therefore a simple, valuable defensive task. In this lecture you learn to work with dates in Python and build a tool that warns before certificates expire. The certificate information is sample data included in the script.
We begin with the datetime module. You will create date objects, get the current date, compare dates and subtract one from another to get a difference, from which you can read the number of days. We discuss parsing dates from text using a format string, because certificate details and logs present dates as text, and we practice a few common formats.
Next we define the check. We store a small list of fictional services with their expiry dates. For each, the tool calculates the days remaining and classifies the situation: expired, critical when only a few days remain, a warning when a month remains and healthy otherwise. We use the elif structure and named thresholds that can be adjusted.
The output is a sorted report that lists the most urgent items first, with clear wording. We discuss time zones and why comparisons should be done consistently, preferably in universal time.
We also describe how a real tool could read a live certificate using the ssl module, while we keep the exercises offline and on systems you are authorized to inspect.
By the end of this lecture you will be able to calculate days until expiry and flag certificates that need renewal.
Looking Up Indicators in Threat Intelligence Data. Threat intelligence is information about addresses, domains and file hashes that have been associated with malicious activity. Defenders compare their own logs against such lists to spot known bad indicators. In this lecture you build a lookup tool that does so, using a small sample dataset of invented indicators.
We begin by designing the data. Each indicator has a value, a type such as address, domain or hash, a category, a confidence level and a source. We store them in a dictionary keyed by value, because a dictionary lookup is fast and direct, and we discuss normalizing values, for instance converting domains to lowercase, so that matches are not missed because of capitalization.
You will write a function that checks a single value and returns the matching record or nothing. Then you extend it to scan a list of observed values, such as addresses taken from a log, and produce a list of matches with the context needed for triage. We use your earlier validation functions so that malformed values are handled cleanly.
We discuss using intelligence responsibly. Indicators age, so a match with an old entry may be stale. Shared addresses can be innocent, and confidence levels matter. A match is a lead for investigation, not a conclusion. We include the age and confidence in the report.
We also mention that real feeds come in files or through services, and that the same lookup approach scales to them.
By the end of this lecture you will be able to match observed values against an indicator list and report the results with context.
Building Alert Messages from Findings. Detection tools produce findings, but findings only help when someone reads and acts on them. An alert is a finding turned into a clear message with enough context to decide what to do. In this lecture you convert the structured findings from earlier lectures into well-formed alerts with severity levels.
We start by defining what a finding looks like: a dictionary with a type, a subject such as a user, address or file, a count or detail, and a source. We then define severity levels, for example low, medium, high and critical, and write a function that assigns a level using rules you can read and defend, such as the number of failures, whether an address is on an indicator list or whether a changed file is on a protected list.
Next you write the alert builder, using f-strings to produce a consistent message. A good alert states what was detected, where, how serious it is, the evidence and a suggested next step. We compare a poor alert, which says only that something is wrong, with one that gives an analyst a place to begin.
You will learn to sort alerts by severity, group related alerts to reduce noise and avoid flooding a reader with repeated messages. We also discuss that alert wording must never include secrets.
We finish by printing the alerts in order and counting them by severity, which prepares the ground for reporting.
By the end of this lecture you will be able to turn findings into prioritized, actionable alert messages.
Writing Findings to a CSV Report. Alerts on a screen are fleeting, and analysts often want findings in a form they can sort, filter and share. CSV files open in every spreadsheet program, which makes them an ideal format for security reports. In this lecture you write findings to a CSV file using Python's csv module.
We begin with why you should use the module and not build lines by hand. Values may contain commas, quotation marks or line breaks, and the module handles the quoting correctly. You will open a file for writing with the newline setting recommended for the csv module and create a writer object.
The simplest approach writes rows as lists, beginning with a header row. A more convenient approach, DictWriter, takes dictionaries and a list of field names, which fits our findings perfectly. We write a report with columns such as time, severity, type, subject, detail and recommended action, then loop over the findings and write one row each.
You will learn to read the file back with DictReader to check it, and to open it in a spreadsheet to confirm that the columns appear correctly. We discuss choosing consistent column names and ordering, adding a generation timestamp and picking a sensible file name that includes the date.
We also discuss data hygiene. A spreadsheet may interpret text starting with certain characters as a formula, so values from untrusted logs should be sanitized before export. We show a simple way to do so.
By the end of this lecture you will be able to write a clean, safe CSV report from your findings.
Saving a JSON Summary Report. CSV suits spreadsheets, but other tools prefer JSON, a format that preserves structure such as nested lists and dictionaries. Dashboards, ticketing systems and later scripts can read JSON directly. In this lecture you save a summary of your findings as a JSON report, and you read it back to confirm that it is complete.
We begin with a short introduction to the format and how it maps onto Python's types. Dictionaries become objects, lists become arrays and strings, numbers and booleans carry over. You will meet the json module and its two main functions, dumps and loads for working with strings and dump and load for working with files.
We design the summary. It contains metadata, such as the tool name, version and generation time, then totals for events analyzed and findings produced, counts by severity and type and the list of individual findings. We build it as a dictionary from the data created by earlier tools.
You will write it to a file with indentation so that humans can read it, and you will learn to sort keys for consistent output, which helps when comparing two reports. We discuss values that JSON cannot represent directly, such as dates and sets, and show how to convert them first.
We also discuss validating a report on reading, with a check that required keys are present, and a version field that allows the format to evolve safely.
By the end of this lecture you will be able to produce and read back a structured JSON summary report.
Scanning a Log File and Checking File Hashes in One Script. The capstone begins here. Throughout the course you built separate tools for log analysis and file integrity. In this lecture you combine them into a single script that performs both checks and gathers the results in one place. All data is a sample log and sample files that you create yourself.
We start with the design. The script has a configuration section at the top for file locations, thresholds and the list of protected files. Below it are small, tested functions: reading the log, detecting failed logins, counting by address, flagging brute-force patterns, hashing files and comparing them with a baseline. A main function calls them in order and collects every finding in a single list using the common structure from the previous section.
You will learn to organize a larger script. We use clear function names, keep each function focused, pass data in as arguments rather than relying on global variables and add short docstrings. We use the standard pattern that runs the main function only when the file is executed directly, which allows the functions to be imported and tested.
We handle problems sensibly. A missing log or baseline produces a clear message and a finding, not a crash, and a malformed line is counted and skipped.
We run the script on a quiet scenario and on one in which we deliberately alter a protected file and add repeated failures, confirming that both are detected.
By the end of this lecture you will be able to combine several defensive checks into one organized script.
Generating the Final Security Summary Report. The final lecture brings the capstone together. A monitoring toolkit is valuable when it presents what it found clearly to the people who must respond. Here you add the reporting stage, producing a final summary that includes every finding from the combined script. As always, the data is your own sample data.
We begin by reviewing what the reader needs. A manager wants a short overview with totals and the most serious items. An analyst wants details, evidence and suggested next steps. We therefore design a report with a header that has the date and the sources examined, a summary of counts by severity and type, a prioritized list of findings and a closing section of recommended actions.
You will reuse the alert builder, the CSV writer and the JSON writer from earlier lectures. The script writes a readable text summary, a CSV file for spreadsheets and a JSON file for other tools, all with consistent names that include the date. We create an output folder if it does not exist and avoid overwriting earlier reports unintentionally.
We add a final check that reads the saved files back and confirms they contain the expected number of findings, so that the toolkit verifies its own output. We also add a simple exit code, which is zero when there are no serious findings and nonzero otherwise, so that automation can react.
We close the course by reviewing what you built and suggesting practical next steps, such as scheduling the toolkit, adding new detections and keeping all testing within systems you are authorized to examine.
By the end of this lecture you will be able to produce a complete, multi-format security summary from your own toolkit.
This course contains the use of artificial intelligence.
Are you ready to learn Python programming and apply it to the exciting world of cybersecurity, defensive security, and security automation? Welcome to Python for Cybersecurity: Build Defensive Security Tools, a comprehensive, hands-on course designed to help you develop practical cybersecurity skills through real-world inspired coding exercises.
Cybersecurity professionals increasingly rely on Python automation to analyze security logs, monitor systems, identify suspicious activities, detect threats, and reduce repetitive manual tasks. This course teaches you how to build your own defensive security tools from scratch, even if you have never written a line of code before.
Through 10 comprehensive modules and 40 hands-on lessons, you will progress from fundamental Python programming concepts to building a functional cybersecurity monitoring toolkit. Instead of spending hours learning theoretical concepts, you will learn by writing code, solving problems, and developing practical security applications.
You will begin with Python fundamentals, including variables, data types, strings, conditional statements, loops, lists, dictionaries, sets, and functions. Each programming concept is introduced through cybersecurity-related examples, helping you understand how Python can support everyday security operations.
As you advance, you will explore security log analysis, authentication monitoring, suspicious activity detection, and automated security reporting. You will develop Python scripts that process log files, identify failed login attempts, extract IP addresses, and detect potential brute-force activity using threshold-based detection techniques.
The course also covers essential password security, SHA-256 hashing, file integrity monitoring, and security hardening concepts. You will build password strength assessment tools, calculate file hashes, and identify unexpected file modifications using Python.
Dive deeper into network security automation by developing IP address validation tools, port verification utilities, network allowlist checks, and security monitoring scripts. Learn how to identify unexpected network addresses and compare security findings against predefined security policies.
You will also explore web security, API security, HTTP security headers, certificate expiration monitoring, and cyber threat intelligence using sample security data. These practical exercises introduce foundational techniques relevant to Security Operations Centers (SOC), Blue Team cybersecurity, and defensive security operations.
Discover how to transform raw security findings into meaningful information through automated security alerts, severity classification, CSV reporting, JSON processing, and cybersecurity dashboards-ready data.
Throughout this course, you will develop practical skills in:
Python for Cybersecurity
Defensive Security Automation
Security Log Analysis
Cyber Threat Detection
SOC Automation Fundamentals
Blue Team Cybersecurity
Network Security Monitoring
Password Security Assessment
File Integrity Monitoring
Security Incident Detection
Threat Intelligence Analysis
Web and API Security Fundamentals
Security Reporting and Automation
Python Scripting for Cybersecurity
DevSecOps Fundamentals
Finally, you will combine your knowledge into a comprehensive hands-on capstone project, building a mini security monitoring toolkit that analyzes log files, verifies file integrity, identifies suspicious activities, and generates structured security reports.
This beginner-friendly course is ideal for aspiring cybersecurity analysts, SOC analysts, Python developers, IT professionals, system administrators, network administrators, DevSecOps engineers, and anyone interested in defensive cybersecurity.
No previous programming or cybersecurity experience is required. You can complete the exercises using Python and freely available development tools without purchasing expensive security software or cloud subscriptions.
Enroll today and start developing practical Python programming, cybersecurity automation, threat detection, and defensive security skills, one hands-on coding exercise at a time.