A script that counts log lines solves one problem. The bigger gain comes when you stop writing throwaway scripts and start building automation that can be reused, combined and run on its own. This is where intermediate Python comes in: well-defined functions, structured data such as JSON, integration with other systems through APIs and scripts that take parameters instead of carrying hardcoded values.
This is the second guide in the track, and the focus is still defensive: automating operations and analysis tasks that currently eat up someone's time. Think of that useful but rigid script that only works with the file and server you hardcoded into it. The goal is to turn it into a flexible tool that other people on the team can use too.
Reusable functions
The first step is to organize the code into functions. Instead of one long block that does everything, each task gets a function with a clear name and a single responsibility. The code becomes easier to read and test, and you can reuse the same function in another script. A function that reads a log and returns the failures, for example, works for a report as well as for an alert. Here is what it looks like:
def count_failures_by_source(path): counts = {} with open(path, encoding="utf-8") as log_file: for line in log_file: if "Failed password" in line: source = line.split("from ")[-1].split()[0] counts[source] = counts.get(source, 0) + 1 return countsfor source, total in count_failures_by_source("auth.log").items(): print(f"{source}: {total} failures")Notice that the function prints nothing: it returns the data, and the caller decides what to do with the result (print it, save it to a file or trigger an alert). Separating the computation from the action looks like a detail, but it is one of the changes that most improve automation code, because it lets you change the output without touching the logic.
Working with structured data
Much of the data that moves around in security comes in a structured format, and the most common one is JSON: API responses, configuration files and tool exports usually come that way. Python reads and writes JSON natively and hands you the content as dictionaries and lists, structures you already know how to work with. That lets you integrate with practically any modern system. In the example below, the script reads a host inventory and lists the hosts without MFA:
import jsonwith open("hosts.json", encoding="utf-8") as inventory_file: hosts = json.load(inventory_file)without_mfa = [h["name"] for h in hosts if not h.get("mfa")]print("Hosts without MFA:", without_mfa)It takes a few lines to read the inventory, filter what matters and end up with a list you can act on. Note the use of h.get("mfa"): if a host does not have that field, the script treats it as having no MFA instead of stopping with an error. The same pattern works for reviewing configurations, cross-referencing data from different sources and generating reports, tasks that take an afternoon by hand and run in seconds in Python.
Integrating systems through APIs
Many security tools and cloud services offer an API, and that is how you query data, check status and automate actions without clicking through an interface. In Python, the requests library makes these calls simple. The main thing to watch is authentication: the access key or token comes from an environment variable, never from a line of code, as in:
import osimport requeststoken = os.environ["API_TOKEN"]response = requests.get( "https://api.example.com/v1/status", headers={"Authorization": f"Bearer {token}"}, timeout=10,)response.raise_for_status()print(response.json())Two details make a difference in this code. The timeout keeps the script from hanging forever while it waits for a service that does not respond. The raise_for_status call stops execution with a clear error when the API returns a failure, instead of letting the script carry on with invalid data. In automation, it is much better to stop early and say so than to keep going silently and deliver a wrong result.
Recording execution with logging
A script that runs on its own needs to leave a record of what it did. When you replace print calls with the standard library's logging module, you control each message's level, its format (with date and time) and its destination, which can be the terminal or a file. When something goes wrong at three in the morning, that record shows what happened, so you do not have to reproduce the problem in the dark. A simple configuration is enough:
import logginglogging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s",)log = logging.getLogger("host_check")log.info("Starting the host check")log.warning("Host without MFA found: web-03")Now, be careful about what goes into the log. Never log passwords, tokens or sensitive personal data: the log file is usually far less protected than the original secret and ends up becoming a source of leaks. Log enough to investigate and stop there, so the log does not create a new privacy problem.
Parameterized and scheduled scripts
A script with hardcoded values works for one case only. Once it accepts parameters, such as a file path or an environment name, the same script becomes a tool that covers several cases. The argparse module in the standard library handles this and also generates help text automatically, so other people can use your script without reading the code.
Once the script is ready and reliable, the next step is to schedule it, so the check happens without depending on someone remembering to run it. At this point the security precautions matter more, because nobody will be watching: the scheduled script needs protected secrets, the least privilege possible and a record of what it did. That is what lets you trust what runs on autopilot.
Taking the next step in the track
To write automation like this, you need to be comfortable with functions, data structures and error handling. That knowledge is what lets you move beyond the copied example and build your own tool. If your basics are solid, Valor Final's Curso de Python Intermediário (in Portuguese) covers exactly this range.
It is the second course in the free track. It is aimed at people who already know variables, conditionals, loops, lists and functions, and it goes deeper into structuring real code. That is the foundation for the automation in this guide and in the next one, which covers building larger tools that last.
Practical checklist
- Split the code into single-responsibility functions
- Have functions compute and return the result, leaving the action to the caller
- Read and write structured data in JSON
- Integrate systems through APIs with the requests library
- Use a timeout and check for errors on every API call
- Read secrets from environment variables
- Accept parameters with argparse instead of hardcoded values
- Use the logging module instead of print calls to record execution
- Never write passwords, tokens or sensitive data to the logs
- Log what the script does when it runs on a schedule
Best practices
- Separate computation from action: the function returns the result and the caller decides what to do
- Read JSON with the json module instead of slicing the text by hand
- Make the automation stop with a clear error as soon as something unexpected happens
- Parameterize the script so it covers several cases
- In scheduled scripts, protect secrets and reduce privileges
Common mistakes
- Writing one long block that does everything
- The code becomes hard to read, test and reuse in another script.
- Calling an API without a timeout
- If the service does not respond, the script sits there waiting forever.
- Ignoring the error code the API returns
- The automation keeps going with invalid data and delivers a wrong result.
- Hardcoding paths and environments
- The script covers one case only and has to be edited every time you use it.
Valor Final's Python track (in Portuguese)
Valor Final's Python track has three free courses, all taught in Portuguese. For the automation in this guide, the intermediate course is the right step once your basics are solid.
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.