Python for Security

Learn enough Python to parse logs, call APIs, work with files and sockets, and write your own small security tools.

Beginner · about 20 hours · difficulty 2/5

Learn first: Linux Command Line Essentials

Python is the most common language in security: detection pipelines, exploit proofs of concept, forensics tools and SOC automation are all written in it. You do not need to be a software engineer, but you must be able to write and read scripts of a few hundred lines.

What to learn first

  • Variables, strings, lists, dicts, loops, functions and error handling.
  • Files: reading logs line by line, writing CSV or JSON reports.
  • Regular expressions (re) for pulling IPs, emails and hashes out of text.
  • Modules from the standard library: os, pathlib, subprocess, hashlib, json, argparse, socket.
  • Third-party packages via pip and virtual environments: requests for HTTP APIs is the big one.

Security-flavored practice

  • Parse an auth log and count failed logins per IP.
  • Hash every file in a folder and compare against a known list.
  • Query a threat-intel API (like VirusTotal's free tier) for a list of hashes.
  • Write a simple TCP port checker with socket for your own lab.

Pitfalls

  • Hardcoding API keys in scripts you push to GitHub. Use environment variables.
  • Using eval or shell=True with untrusted input; you just built a command injection bug.

Good enough to move on: you can write a script with command-line arguments that reads a log file, extracts indicators with regex, and outputs a clean JSON summary.

Key concepts

  • Core syntax and data structures
  • File and log parsing
  • Regular expressions
  • argparse CLIs
  • requests and REST APIs
  • socket basics
  • hashlib and file hashing
  • Virtual environments and pip

Other options for this step

  • Bash Scripting for Security: Automate Linux tasks with Bash scripts: loops, conditionals, pipelines and quick one-off tools for log triage and recon in labs.
  • PowerShell for Security: Use PowerShell to query Windows systems, event logs and Active Directory, and understand why attackers love it too.

Mini project

Build a CLI that takes an auth log, extracts failed login IPs, counts them, and flags any IP above a threshold, writing results to JSON.

Check yourself

Why is subprocess.run(user_input, shell=True) dangerous, and how would you rewrite it safely?

Free resources