Open the tools, scripts and notebooks that get passed around a security team and you will find Python in almost all of them. It has become the common language of people who automate tasks, analyze logs, integrate systems or need to test an idea quickly. The reason is practical: the code is easy to read, the standard library already covers a lot, and for whatever is missing there is almost always a package. That shortens the path from having an idea to having a working script.
This is the first of three guides on Python applied to security, and it starts from scratch. First we look at why Python fits security and automation so well. Then we set up an environment that works the same way on another machine, see what the standard library already handles and write the first scripts worth the effort. The examples stay on the defensive side (reading logs, checking configurations, automating repetitive tasks), and the material contains no attack instructions.
Why Python in security
Python's first advantage in security is its syntax. A script one person writes is easy for another to read and adjust, which matters a lot when code changes hands within a team. The standard library helps too: handling files and dates, making requests and reading JSON are things you can do without installing anything. And when it falls short, someone has almost always published a library for the problem.
Then there is the nature of the work. Much of what a security team does day to day is data handling: take a pile of logs, filter it, count, cross-reference it with another source and summarize. Python does this in a few lines, and the script that counts suspicious access attempts today can become a step in an automated process tomorrow. For the effort it takes to learn, the return is high.
Setting up the environment
You need very little to start: a recent version of Python and a text editor are enough for your first scripts. As the work grows, two habits save a lot of headaches. The first is using a virtual environment to isolate the dependencies of each project. The second is pinning the versions of the libraries your script uses.
A virtual environment keeps one project's libraries separate from another's. Without it, upgrading a package for one project can break a different one, and reproducing the script on another machine gets hard. Pinning versions solves a different problem: it keeps a library update from changing how your code behaves without you noticing. With these two precautions, the script runs on other machines, not only on yours. To create and activate the environment and install a package, the commands are:
python -m venv .venvsource .venv/bin/activate # on Windows: .venv\Scripts\activatepip install requestsRecord your dependencies
As soon as the script depends on an external library, record it in a dependency file. The pip freeze command writes the exact versions to a requirements.txt, and whoever runs the script later rebuilds the same environment with pip install from that file. It takes a few seconds, and it is what makes the script behave the same way on your machine, on a colleague's and on the server where it will run on a schedule.
Your first defensive script
The best first script is one that solves a problem you already have. A classic example is counting failed login attempts in an authentication log. By hand, that is tedious and easy to get wrong. In Python, it takes a few lines that you can run whenever you need, as in:
# counts failed login attemptsfailures = 0with open("auth.log", encoding="utf-8") as log_file: for line in log_file: if "Failed password" in line: failures += 1print(f"Failed login attempts: {failures}")The script is simple, and that is exactly the point: a manual, repetitive task now runs in a second, the same way every time. From here you can group the failures by source address, filter by time or export the result, and that kind of progression is what the rest of the Python track covers.
The standard library already does a lot
Before you install any package, look at what already ships with Python. Many security tasks can be handled with the standard library: pathlib deals with file paths, json and csv read structured data, datetime helps you work with time windows, ipaddress validates addresses and networks, and collections.Counter counts occurrences without you writing the counting logic by hand. Knowing these tools keeps you from reinventing what the language already provides. Here is how Counter improves the previous script:
from collections import Countersources = Counter()with open("auth.log", encoding="utf-8") as log_file: for line in log_file: if "Failed password" in line and "from " in line: source = line.split("from ")[-1].split()[0] sources[source] += 1for source, total in sources.most_common(10): print(f"{source}: {total} failures")With a few more lines, the script shows the ten sources with the most failures, already sorted. Note that the sorting comes from most_common; you did not write any logic for it. That kind of cheap gain is what makes time spent studying the standard library pay off. When it does not cover the task, you turn to an external package, but starting with what already exists keeps the script simple and free of unnecessary dependencies.
Writing scripts responsibly
Security automation touches sensitive data and systems, so a few precautions apply from the very first script. Passwords, tokens and keys should not be written in the code: read those values from environment variables or a secrets vault. Think twice before running a script with high privileges, because a logic error (a loop that deletes too many files, for example) does damage in proportion to the privilege. And test in a controlled environment before you point the script at production.
- Never write passwords, tokens or keys in the code
- Read secrets from environment variables or a vault
- Run with the least privilege the task needs
- Test in a controlled environment before using it in production
- Handle errors so the script fails predictably
It may seem like overkill when you are starting out, but these habits cost little and prevent exactly the problems that show up when a script stops being an experiment and becomes part of operations. From that point on, the defensive script runs on its own with nobody watching, and you need to trust what it does.
Learning the basics the right way
To write useful scripts, you need a solid grasp of the language basics: variables, conditionals, loops, lists and functions. With that foundation, a ready-made example stops being something to copy and becomes a starting point for your own code. Without it, you are stuck with copy and paste and do not know what to change when the problem is slightly different.
If you have never programmed, Valor Final's Curso de Python Básico (a beginner course in Portuguese) is a good starting point. It is free, runs right in the browser (you do not need to install anything) and has you writing real code in the very first lesson. The next guides in this track, which focus more on automation and building tools, assume this foundation.
Practical checklist
- Install a recent version of Python and a text editor
- Use one virtual environment per project
- Record dependencies and versions in a requirements.txt
- Get to know the standard library: pathlib, json, csv, datetime, ipaddress, Counter
- Write a first script that solves a problem you already have
- Read secrets from environment variables instead of leaving them in the code
- Run scripts with the least privilege necessary
- Test in a controlled environment before production
- Master variables, conditionals, loops, lists and functions
Best practices
- Start by solving a problem you already have
- Isolate dependencies with a virtual environment early on
- Keep secrets out of the source code
- Prefer small, readable scripts over clever solutions nobody understands later
- Handle errors so the script fails predictably
Common mistakes
- Storing passwords and tokens inside the script
- A secret written in the code leaks easily, especially once the file goes into version control.
- Running scripts with administrator privileges when they do not need them
- Any logic error gets administrator reach and can cause widespread damage to the system.
- Installing everything into the system Python, without a virtual environment
- Version conflicts break one project when you change another.
- Copying code without understanding the language basics
- When the problem changes slightly, you do not know how to adapt the script.
Valor Final's Python track (in Portuguese)
Valor Final's Python track goes from zero to advanced and is free. The courses are taught in Portuguese. If you are just starting, the first course has you writing code in the first lesson, right in the browser.
Curso de Python Básico
FreeFree Python course for people who have never programmed. From the very first lesson you write real code, right in the browser, without installing anything. Course in Portuguese.
Valor Final View courseCurso de Python Intermediário
FreeSecond course in the track. It is for people who already know the basics (variables, conditionals, loops, lists and functions) and want to keep going. Course in Portuguese.
Valor Final View courseCurso de Python Avançado
FreeThird course in the track. It is for people who already write well-organized code and want to go deeper into object-oriented programming, decorators, generators and testing. Course in Portuguese.
Valor Final View course
Authorship and review
Cesar Gargiulo
CEO and founder of GUARDIASEC. Technical and editorial lead for the content published in this library.
Published on . Found a technical error? Write to [email protected] and we will correct it and keep a record of the change.