
Every security tool in this course is a Python program, so the first job is to make sure Python is installed correctly and that you know exactly which version you are running. Security libraries can depend on a recent interpreter, and a mismatch causes confusing errors later. In this lesson you will check your Python install and run your first script.
You will begin in a terminal. You will run the command that prints the Python version, learn the difference between the python and python3 commands on different systems, and find out where the interpreter lives on your machine. If the version is too old or the command is not found, you will see what to do about it.
Next you will open a code editor, such as Visual Studio Code, and create a new file called hello_security.py. You will write a short script that prints a message, and use the sys module to print the version and the platform from inside Python. This is a small habit that will help you diagnose problems throughout the course.
You will then run the script from the terminal and from the editor, and compare the two. You will read the output carefully, and learn how to recognise the most common first-time errors, such as a typo in the file name, running the command from the wrong folder or a missing quotation mark.
You will finish by creating a working folder for the course, so that every project you build has a tidy home.
By the end of this lesson you will be able to confirm your Python version and run a script from the terminal and your editor.
Security tools often need specific package versions, and installing them globally can break other projects on your computer. A virtual environment solves this by giving each project its own private set of packages. In this lesson you will create and activate a virtual environment for your security workspace.
You will begin with the reason. Without isolation, a package installed for one project can silently change the behaviour of another, and you lose track of what a project really needs. A virtual environment is simply a folder that holds its own interpreter link and its own installed packages.
Next you will create one with the venv module from the terminal, naming the folder in a way that is easy to recognise. You will look inside the folder and find the scripts or bin directory and the configuration file that Python uses to remember the setup.
You will then activate the environment. You will see the exact command for Windows, macOS and Linux, and learn how to tell that it worked, because the prompt changes and the python command now points inside the folder. You will check this by printing the path of the interpreter.
You will practise deactivating and reactivating it, and talk about common problems, such as execution policy messages on Windows and forgetting to activate before installing a package.
You will also discuss why you should not commit the environment folder to version control.
By the end of this lesson you will be able to create, activate and deactivate a virtual environment for a project.
Python becomes powerful through packages, the shared libraries that other people have written. The standard tool for installing them is pip. In this lesson you will install a package with pip and learn how to do it safely, which matters especially in security work where trust in your tools is important.
You will begin by making sure your virtual environment from the previous lesson is active, and then checking which pip you are using. You will install a small, well-known package and watch the output, learning to read the messages about downloading and installing.
Next you will explore what pip can tell you. You will list the packages installed, show the details of one package, such as its version and where it is installed, and upgrade and uninstall a package. You will confirm each change by importing the package in a short script.
You will then talk about safe habits. You should install only packages you actually need, check the exact spelling of the package name, because look-alike names are a known way to trick people, and prefer well-maintained projects with a clear history. You will learn why you should be careful about running install commands copied from unknown sources.
You will also deal with typical errors, such as a package that cannot be found or a permissions problem, and see how the virtual environment prevents the need for administrator rights.
By the end of this lesson you will be able to install, inspect and remove packages with pip and apply safe installation habits.
Once you start installing packages, you need a way to record them so that your project can be rebuilt on another machine or at a later date. The standard answer is a requirements file. In this lesson you will organise your security workspace with a requirements file.
You will begin by looking at the problem. If you simply remember what you installed, you will eventually forget, and a colleague or a future version of you will not be able to run your tools. A requirements file is a plain text file that lists the packages and their versions, one per line.
Next you will create one by exporting the current environment with pip freeze and writing the output to requirements.txt. You will open the file and read the format, and learn what the double equals sign means and why pinning versions makes your results repeatable.
You will then prove that it works. You will create a second, fresh virtual environment, install everything from the file with pip install and the dash r option, and compare the two lists of packages.
You will also design a tidy workspace layout, with folders for scripts, sample data and reports, and a short README that explains how to set it up. You will talk about keeping real secrets out of the workspace and using sample data only.
You will finish by adding comments to the requirements file to explain why each package is there.
By the end of this lesson you will be able to record, share and reproduce a project's dependencies and keep a clean workspace.
Security scripts handle many kinds of data: a number of failed logins, an IP address, a username, a flag that says whether an account is locked. Variables are how Python remembers them. In this lesson you will store security data in variables.
You will begin with the basics of assignment. You will create variables for a hostname, a port number, a count of failed login attempts and a true or false flag, and print each one. You will learn the main data types, which are strings, integers, floats and booleans, and use the type function to check what you have.
Next you will see why the type matters. You will try to add a number to a string and read the error that Python gives, and then fix it with a conversion using int and str. You will use this in a small example that reads a port number as text and converts it to a number before comparing it with a limit.
You will practise good naming, using clear lowercase names with underscores, such as failed_attempts, and explain why names like x make security code hard to review. You will also use constants in capital letters for values that should not change, such as a maximum number of attempts.
You will build a small script that stores several pieces of sample data, formats them into a readable line with an f-string and prints a mini status report.
By the end of this lesson you will be able to store and convert basic data types and name variables clearly.
Almost all security data starts as text. Log lines, URLs, email subjects and file paths are all strings. Being comfortable with strings is therefore one of the most useful skills for a security scripter. In this lesson you will work with strings using sample log lines.
You will begin with a synthetic log line that contains a date, a level, a username and a message. You will print it, find its length and use indexing and slicing to pick out parts of it. You will see that Python counts from zero and use negative indexes to read from the end.
Next you will learn the string methods you will use all the time: lower and upper to change case, strip to remove spaces, split to break a line into pieces, join to put pieces back together, replace to change text and startswith and endswith to test the beginning and end. You will try each on the sample line.
You will use the in operator to check whether a word such as FAILED appears in a line, and the find method to locate it. You will then use f-strings to build neat output with the values you extracted.
You will discuss why strings cannot be changed in place, and what that means when you edit them.
You will finish with a short exercise that takes five sample log lines and prints only those that contain a chosen keyword, in upper case.
By the end of this lesson you will be able to slice, search, split and format strings in security scripts.
Security work often means dealing with groups of things: a list of IP addresses, a set of usernames or a collection of file names. Lists are the basic tool for this in Python. In this lesson you will collect items in lists and use them on sample security data.
You will begin by creating a list of sample IP addresses from reserved documentation ranges, so that no real systems are involved. You will print it, check its length with len and read items by index and by slice.
Next you will change the list. You will add items with append and insert, remove them with remove and pop, sort them with sort and sorted and reverse them. You will see the difference between a method that changes the list in place and a function that returns a new one.
You will use the in operator to test whether an address is already in a list, and see how that helps you avoid duplicates. You will also look at list comprehensions as a compact way to build a new list, for example one that holds only the addresses that begin with a certain prefix.
You will learn about the common pitfall of copying a list. Assigning one name to another does not make a copy, so you will use the copy method and a slice to make a real one, and show the difference with an example.
You will end with a small script that builds a blocklist, adds new entries, removes duplicates with set and prints a sorted result.
By the end of this lesson you will be able to create, change, search and copy lists safely.
Lists are good when order matters, but security data often comes as pairs: a port and its service, a username and its number of failed attempts, a header name and its value. Dictionaries store such pairs and let you look up a value by its key. In this lesson you will look up values with dictionaries.
You will begin by creating a dictionary that maps common port numbers to service names, such as 22 to SSH and 443 to HTTPS. You will print it, read a value with square brackets and see the KeyError that appears when a key is missing.
Next you will use the get method with a default to look up a key safely, and use the in operator to check for a key first. You will compare the two approaches and discuss when each is clearer.
You will change the dictionary by adding, updating and deleting entries, and loop through it with keys, values and items. You will use a dictionary to count events, such as how many times each username appears in a list of sample failed logins, and print the results sorted from most to least frequent.
You will meet nested dictionaries by storing several details for each user, and look up a value inside one. You will also learn that dictionary keys must be hashable, and which types are suitable.
You will finish with a small script that reads a list of sample ports and reports the service name for each, or Unknown if it is not in the table.
By the end of this lesson you will be able to build, search, update and count with dictionaries.
A security tool becomes useful when it can repeat an action for every item and make decisions along the way. Loops and conditions provide this. In this lesson you will repeat and decide with for loops, while loops and if statements, using sample security data.
You will begin with the if statement. You will write a check that compares a count of failed logins with a threshold and prints a message depending on the result, and extend it with elif and else branches. You will practise comparison operators and the logical words and, or and not, and learn why indentation is part of Python syntax.
Next you will write a for loop that goes through a list of sample log entries and prints each with its number, using enumerate. You will use range to repeat an action a fixed number of times, and learn the meaning of break to stop early and continue to skip an item.
You will then write a while loop that keeps going until a condition changes, such as a simulated lockout counter reaching a limit. You will see how an unchanging condition makes an endless loop, and how to stop one with a keyboard interrupt.
You will combine loops and conditions in a small script that goes through a list of sample login events, counts the failures, flags any account that crosses a threshold and prints a summary.
You will finish by tidying the script with clear names and comments.
By the end of this lesson you will be able to use loops and conditions to process collections and make decisions.
As your scripts grow, repeating the same code in many places becomes a problem. If you find a mistake, you have to fix it everywhere. Functions solve this by packaging a piece of logic under a name that you can call whenever you need it. In this lesson you will package logic into functions.
You will begin with a short piece of code that checks whether a port number is in the list of well-known ports. You will turn it into a function with the def keyword, give it a parameter and a return value, and call it with several inputs. You will see the difference between printing a result and returning it, and why returning is more useful.
Next you will learn about parameters in more depth. You will use default values, keyword arguments and type hints, and write a docstring that explains what the function does. You will use help to read your own documentation.
You will discuss scope, which means where a variable can be seen, and avoid changing global values from inside a function. You will also write a function that returns more than one value as a tuple and unpack it.
You will then build a few small helper functions for later lessons, such as one that normalises a username, one that counts failures and one that formats a report line. You will test each with a handful of simple checks using assert.
By the end of this lesson you will be able to write, document and test your own functions and use them to avoid repeated code.
Real security analysis starts with a log file on disk, and logs can be very large. Reading a whole file into memory is wasteful and sometimes impossible, so the usual approach is to read it line by line. In this lesson you will read a log file line by line.
You will begin by creating a small synthetic log file with a few dozen lines, each with a timestamp, a level, a user and a message. You will use sample data only, so no real systems or people are involved. You will save it in your data folder.
Next you will open the file with the open function inside a with statement, and explain why the with statement is the right choice, since it closes the file for you even if an error occurs. You will read the file in three ways, with read for everything, readlines for a list and a for loop for one line at a time, and discuss why the loop is best for large logs.
You will learn about the newline character at the end of each line and remove it with strip. You will count the lines, skip blank ones and print the first few entries with line numbers.
You will handle errors properly. You will catch FileNotFoundError and PermissionError, print a helpful message and exit cleanly, rather than letting a long traceback appear. You will also learn to specify the encoding.
By the end of this lesson you will be able to read a log file safely and efficiently, one line at a time.
A log line is just text until you split it into meaningful pieces. Only then can you count, filter and compare. In this lesson you will parse log lines into fields and build structured records from them.
You will begin by examining the format of your synthetic log, which has a date, a time, a level, a source address and a message. You will take one line and split it with the split method, and see that the approach works for simple lines but becomes fragile when the message itself contains spaces.
Next you will improve it. You will use split with a maximum number of splits, so the message stays together, and then try a regular expression with named groups for a more robust result. You will explain the pattern in plain words and test it against lines that match and lines that do not.
You will write a function called parse_line that takes one line and returns a dictionary with keys such as timestamp, level, source and message, or None if the line does not match. You will explain why returning None is a clear way to signal a problem.
You will use the function on the whole file, build a list of dictionaries and count how many lines parsed correctly and how many did not. You will print the malformed ones for review, because ignoring them could hide problems.
You will convert the timestamp into a datetime object with the datetime module so that you can sort by time.
By the end of this lesson you will be able to turn raw log lines into structured, reliable dictionaries.
With parsed log entries, the next step is to find the ones worth a human's attention. Filtering is at the heart of defensive monitoring. In this lesson you will filter log entries for suspicious activity.
You will begin by deciding what suspicious means in a simple, explainable way. Your rules will be easy to read: entries at an error or warning level, messages that mention failed logins, access attempts outside working hours and sources that appear many times in a short period. You will say clearly that these are teaching rules, and that real monitoring needs rules tuned to a real environment.
Next you will write filter functions that take the list of parsed entries and return only those that match a rule. You will use list comprehensions and a helper function for each rule, and give each a clear name. You will test them on your sample log and check the counts by hand.
You will then count events per source address with a dictionary, and report the sources that exceed a threshold. You will use the collections module and its Counter class to do this more neatly, and print the top five.
You will combine the rules and tag each entry with the reasons it was flagged, so that a reader can see why it appears in the output.
You will discuss false positives and why a flagged line is a lead for investigation, not a conclusion.
By the end of this lesson you will be able to apply clear, explainable filters to log data and report flagged entries with reasons.
Analysis is only useful if you can share the results. A report file turns your findings into something that can be reviewed, stored and sent to others. In this lesson you will write results to a report file.
You will begin by deciding on the contents of a report. You will include a title, the time it was created, the name of the log that was analysed, the number of lines read, the number flagged and a table of the flagged entries with the reason for each. You will keep everything based on your synthetic sample data.
Next you will write a plain text report using open in write mode inside a with statement. You will learn the difference between write mode, which replaces a file, and append mode, which adds to it, and see how choosing the wrong one can destroy earlier results. You will format the output with f-strings so that columns line up.
You will then write the same data in two more useful formats. You will produce a CSV file using the csv module and its DictWriter, and a JSON file using the json module with indentation. You will open each in a viewer or editor and discuss the best use for each format.
You will include the creation time using datetime, and put a timestamp in the file name so that earlier reports are not overwritten. You will use pathlib to create the reports folder if it does not exist.
You will also talk about not putting sensitive data in reports.
By the end of this lesson you will be able to write clear text, CSV and JSON reports safely.
So far your scripts have used fixed file names written in the code. Real tools need to accept input from the person who runs them, so they can be pointed at different files without editing the source. In this lesson you will accept command-line arguments.
You will begin with the simplest tool, sys.argv, which is a list of the words typed after the script name. You will print it, read the first argument as a file name and see what happens when the user forgets to provide one. You will use this to understand why a more careful approach is needed.
Next you will use the argparse module from the standard library. You will create a parser, add a positional argument for the log file path, an optional argument for the threshold and a flag for verbose output. You will set types and default values, and write a short help text for each.
You will see that argparse generates a usage message for free, and run your script with the dash h option to read it. You will also see how it reports errors, such as a missing argument or a value of the wrong type.
You will then connect the arguments to your earlier code, so that the same script analyses any log file and writes a report to a chosen output folder. You will validate the paths and give clear errors.
You will finish by running the tool with several combinations of options.
By the end of this lesson you will be able to build a command-line interface for your scripts using argparse.
This course contains the use of artificial intelligence.
Are you ready to explore the powerful combination of Python Programming, Cybersecurity, Artificial Intelligence, Generative AI, and Machine Learning through practical, hands-on projects?
Welcome to Build 15 AI Security Tools with Python, a beginner-friendly, project-based course designed to help you develop practical cybersecurity automation tools, analyze security threats, process security data, and explore intelligent security applications using Python.
As cybersecurity threats become increasingly sophisticated, organizations need professionals who understand both Artificial Intelligence and Cybersecurity. Learning how to combine these technologies can help you develop valuable skills in Security Automation, Threat Detection, Security Engineering, and AI-Powered Cybersecurity.
This course takes a hands-on approach, allowing you to learn by writing code, experimenting with security scenarios, and developing reusable security tools rather than simply memorizing theoretical concepts.
You will begin with Python Programming Fundamentals, including environment setup, variables, strings, lists, dictionaries, loops, conditional statements, and functions. Every programming concept is introduced through security-focused examples, helping you understand how Python can support real-world cybersecurity workflows.
As you progress, you will explore Security Log Analysis, File Handling, Log Parsing, Suspicious Activity Detection, Command-Line Programming, and Automated Security Reporting. You will learn how to transform raw security data into meaningful information that supports security investigations.
Next, you will develop practical Python Cybersecurity Tools for Password Strength Analysis, SHA-256 Hashing, File Integrity Monitoring, Regular Expressions, and Security Pattern Detection. These exercises introduce essential defensive cybersecurity techniques while strengthening your Python programming skills.
The course also introduces Network Security, Web Security, HTTP Security Headers, URL Analysis, Port Numbers, JSON Processing, REST API Concepts, and Sensitive Data Detection. You will explore how security-focused applications can identify potentially risky configurations and exposed information using authorized environments and sample data.
Moving into Generative AI for Cybersecurity, you will explore Large Language Models (LLMs), Prompt Engineering, Few-Shot Learning, Structured AI Outputs, API Key Management, Response Validation, and AI Security Automation.
Through practical exercises and simulated model responses, you will develop prototypes for AI-Assisted Phishing Detection, Security Alert Triage, Intelligent Log Summarization, and Security Alert Prioritization.
You will also discover how Machine Learning for Cybersecurity works by building a spam classification model using scikit-learn, Natural Language Processing (NLP), Bag-of-Words, CountVectorizer, and Naive Bayes Classification. Learn how to train and evaluate machine learning models using Training and Testing Datasets, Accuracy Scores, False Positives, and False Negatives.
Finally, bring your skills together by developing a Command-Line Security Assistant that integrates multiple security tools, reusable Python modules, command dispatching, and consolidated security reporting.
Key technologies and skills covered include:
Python for Cybersecurity and Security Automation
Artificial Intelligence and Generative AI
Machine Learning and Natural Language Processing
Phishing Detection and Spam Classification
Security Operations Center (SOC) Automation Concepts
Password Security and File Integrity Verification
Prompt Engineering and LLM Integration Concepts
Security Monitoring and Log Analysis
Defensive Cybersecurity and Threat Detection
Python Scripting and Command-Line Tool Development
Whether you are a beginner, aspiring Cybersecurity Analyst, Python developer, IT professional, security enthusiast, or aspiring AI Engineer, this course provides a practical foundation for combining programming, security, and artificial intelligence.
No previous programming or cybersecurity experience is required. Start building practical security projects, strengthen your technical portfolio, and discover how Python and AI can support modern cybersecurity workflows.