Python for Cybersecurity: Write Your First Security Script

Learn Python for cybersecurity from scratch. Build your first port scanner, log parser, and hash checker with practical scripts SOC analysts actually use.
- Defense
- Detection
- Skills
- Automation
- Career Paths
TL;DR
Python is the most widely used programming language in cybersecurity, appearing in 72% of security tool development and SOC automation workflows. This guide walks beginners through writing their first security scripts: a TCP port scanner, a log file analyzer, and a file hash integrity checker. No prior programming experience is required, just a willingness to type code and run it.
It was 6:14 PM on a Friday when Marcus, a junior SOC analyst three months into his first security job, noticed something odd. The SIEM dashboard showed 847 failed login attempts against the same user account across a 90 minute window. Different source IPs. Same target. A textbook credential stuffing attack. His senior colleague had already left for the weekend. The runbook said to extract all source IPs, cross reference them with threat intelligence feeds, and block confirmed malicious addresses at the firewall. Manually copying 847 log entries, extracting IPs one by one, and checking each against a threat feed would take hours.
Marcus opened a terminal and wrote 23 lines of Python. The script parsed the log file, extracted unique source IPs, checked each one against an open threat intelligence API, and generated a blocklist of confirmed malicious addresses. Total runtime: 11 seconds. What would have consumed his entire evening became a solved problem before he finished his coffee.
That script was not elegant. It had no error handling, no logging, no command line arguments. It was functional, fast, and it solved a real problem. That is what Python for cybersecurity looks like in practice. You do not need to be a software engineer. You need to be someone who can translate a security problem into working code.
Why Python Dominates Cybersecurity
Python holds a unique position in the security world because it sits at the intersection of simplicity and power. The SANS Institute identifies Python as the most recommended language for security professionals, noting that its readable syntax allows analysts to write functional tools without years of programming education.
Three characteristics make Python the default choice. First, its standard library includes modules for networking, file handling, cryptography, and HTTP communication. You can build a port scanner, parse log files, or interact with web APIs without installing a single external package. Second, Python runs on every platform security professionals encounter: Linux, Windows, macOS, and even embedded systems. A script written on your laptop works identically on a remote server. Third, the security community has built thousands of libraries specifically for offensive and defensive work, from Scapy for packet crafting to Volatility for memory forensics.
The practical impact is measurable. According to a 2025 SANS survey, SOC teams that automate repetitive tasks with scripting reduce their mean time to respond (MTTR) by up to 40%. When a threat emerges at 2 AM, the difference between a 45 minute manual response and an 11 second automated one is the difference between containment and breach.
Setting Up Your Python Security Environment
Before writing any code, you need a working Python installation and a text editor. If you are running Kali Linux or any modern Linux distribution, Python 3 is already installed. Verify by opening a terminal and typing:
python3 --version
On Windows or macOS, download Python from python.org. During installation on Windows, check the box labeled "Add Python to PATH." This step is critical. Without it, your terminal will not recognize the python command.
For writing scripts, any text editor works. VS Code with the Python extension provides syntax highlighting, error detection, and an integrated terminal. Beginners often do well with simpler editors like Nano on Linux or Notepad++ on Windows. The tool matters less than the habit of actually writing code.
Create a dedicated directory for your security scripts:
mkdir ~/security-scripts
cd ~/security-scripts
Every script in this guide runs with Python's standard library. No pip installs required for your first three projects.
Your First Script: TCP Port Scanner
Port scanning is fundamental to penetration testing and network reconnaissance. Before you can test a system's security, you need to know which services are running and which ports are open. While tools like Nmap handle this professionally, building your own scanner teaches you how TCP connections actually work.
A TCP connection starts with a three way handshake. Your machine sends a SYN packet, the target responds with SYN-ACK if the port is open, and your machine completes the handshake with an ACK. If the port is closed, the target sends a RST packet instead. Python's socket module handles this entire process.
import socket
import sys
from datetime import datetime
def scan_port(target, port):
"""Attempt a TCP connection to a single port."""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((target, port))
sock.close()
return result == 0
except socket.error:
return False
def scan_target(target, start_port, end_port):
"""Scan a range of ports on the target host."""
print(f"\nScanning {target}")
print(f"Started at {datetime.now().strftime('%H:%M:%S')}")
print("-" * 40)
open_ports = []
for port in range(start_port, end_port + 1):
if scan_port(target, port):
open_ports.append(port)
try:
service = socket.getservbyport(port)
except OSError:
service = "unknown"
print(f" Port {port}: OPEN ({service})")
print(f"\nScan complete. {len(open_ports)} open port(s) found.")
return open_ports
if __name__ == "__main__":
target = input("Target IP or hostname: ")
scan_target(target, 1, 1024)
Save this as port_scanner.py and run it with python3 port_scanner.py. Enter 127.0.0.1 (your own machine) as the target for safe testing. The script attempts a TCP connection on each port from 1 to 1024, reports open ports with their service names, and tells you how many it found.
This scanner is deliberately simple. Production tools like Nmap use raw sockets, SYN scanning, and multi-threaded execution for speed. But this script demonstrates the core concept: a port is open if a TCP connection succeeds. Understanding this foundation makes you a more effective user of professional tools.
Automating Log Analysis With Python
SOC analysts spend a significant portion of their day reading logs. Authentication logs, web server access logs, firewall logs, and application logs all contain evidence of attacks, misconfigurations, and anomalies. Manually reviewing thousands of lines is slow and error prone. Python turns this into a structured, repeatable process.
The following script parses a standard auth.log file, extracts failed SSH login attempts, counts attempts per source IP, and flags IPs that exceed a threshold:
import re
from collections import Counter
def analyze_auth_log(filepath, threshold=10):
"""Parse auth.log for failed SSH attempts and flag suspicious IPs."""
failed_pattern = re.compile(
r"Failed password for (?:invalid user )?(\S+) from (\d+\.\d+\.\d+\.\d+)"
)
attempts = []
usernames_targeted = {}
with open(filepath, "r") as log_file:
for line in log_file:
match = failed_pattern.search(line)
if match:
username = match.group(1)
ip_address = match.group(2)
attempts.append(ip_address)
if ip_address not in usernames_targeted:
usernames_targeted[ip_address] = set()
usernames_targeted[ip_address].add(username)
ip_counts = Counter(attempts)
print(f"Total failed login attempts: {len(attempts)}")
print(f"Unique source IPs: {len(ip_counts)}")
print(f"\nIPs exceeding {threshold} failed attempts:")
print("-" * 55)
flagged = []
for ip, count in ip_counts.most_common():
if count >= threshold:
users = usernames_targeted.get(ip, set())
print(f" {ip:18s} {count:4d} attempts {len(users)} usernames")
flagged.append(ip)
if flagged:
print(f"\nBlocklist ({len(flagged)} IPs):")
for ip in flagged:
print(ip)
return flagged
if __name__ == "__main__":
flagged_ips = analyze_auth_log("/var/log/auth.log", threshold=10)
The re module handles pattern matching with regular expressions. The Counter class from collections counts occurrences automatically. Together, they transform a wall of text into actionable intelligence: which IPs are attacking, how aggressively, and which usernames they are targeting.
This script reveals attack patterns that manual review misses. An IP that tried 200 different usernames is running a dictionary attack. An IP that tried the same username 500 times is brute forcing a specific account. The distinction matters because each pattern requires a different response.
Building a File Integrity Checker
File integrity monitoring detects unauthorized changes to critical system files. When malware modifies a configuration file, replaces a binary, or plants a backdoor, the file's cryptographic hash changes. By comparing current hashes against known good baselines, you detect tampering that might otherwise go unnoticed.
NIST Special Publication 800-53 lists file integrity monitoring as a core security control (SI-7). Python's hashlib module calculates hashes using the same algorithms that enterprise tools rely on.
import hashlib
import os
import json
from datetime import datetime
def hash_file(filepath):
"""Calculate SHA-256 hash of a file."""
sha256 = hashlib.sha256()
try:
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256.update(chunk)
return sha256.hexdigest()
except (PermissionError, FileNotFoundError) as e:
return f"ERROR: {e}"
def create_baseline(directories, output_file="baseline.json"):
"""Create a hash baseline for files in specified directories."""
baseline = {}
file_count = 0
for directory in directories:
for root, dirs, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_hash = hash_file(filepath)
if not file_hash.startswith("ERROR"):
baseline[filepath] = {
"hash": file_hash,
"recorded_at": datetime.now().isoformat()
}
file_count += 1
with open(output_file, "w") as f:
json.dump(baseline, f, indent=2)
print(f"Baseline created: {file_count} files recorded.")
return baseline
def check_integrity(baseline_file="baseline.json"):
"""Compare current file hashes against the baseline."""
with open(baseline_file, "r") as f:
baseline = json.load(f)
modified = []
missing = []
for filepath, record in baseline.items():
if not os.path.exists(filepath):
missing.append(filepath)
continue
current_hash = hash_file(filepath)
if current_hash != record["hash"]:
modified.append({
"file": filepath,
"expected": record["hash"][:16] + "...",
"actual": current_hash[:16] + "..."
})
print(f"\nIntegrity Check Results")
print(f"Files checked: {len(baseline)}")
print(f"Modified: {len(modified)}")
print(f"Missing: {len(missing)}")
if modified:
print(f"\nMODIFIED FILES:")
for entry in modified:
print(f" {entry['file']}")
print(f" Expected: {entry['expected']}")
print(f" Actual: {entry['actual']}")
if missing:
print(f"\nMISSING FILES:")
for filepath in missing:
print(f" {filepath}")
return modified, missing
if __name__ == "__main__":
import sys
if len(sys.argv) > 1 and sys.argv[1] == "check":
check_integrity()
else:
dirs_to_monitor = ["/etc/ssh", "/etc/cron.d"]
create_baseline(dirs_to_monitor)
print("Run with 'check' argument to verify integrity.")
Run python3 integrity_checker.py to create a baseline, then python3 integrity_checker.py check to verify files against it. Any modification, even a single byte change, produces a completely different hash. This is the same principle that powers tools like OSSEC and Tripwire.
The script reads files in chunks of 8192 bytes, which means it handles files of any size without loading them entirely into memory. It stores baselines as JSON, making them human readable and easy to integrate with other tools.
Where Python Fits in Your Security Career
Python is not a replacement for understanding security concepts. It is an amplifier. Knowing how a brute force attack works is valuable. Writing a script that detects one in real time, extracts indicators of compromise, and generates a blocklist is a career differentiator.
For aspiring SOC analysts, Python automates the repetitive tasks that consume investigation time: parsing logs, enriching IOCs with threat intelligence, generating reports, and correlating events across data sources. For penetration testers, Python enables custom exploit development, payload generation, and post exploitation automation. For security engineers, Python scripts integrate tools, automate deployment, and enforce policy.
The path forward follows a clear progression. Master the standard library scripts in this guide. Then explore external libraries: requests for API interaction, scapy for packet manipulation, paramiko for SSH automation. Build tools that solve problems you encounter in your own lab or job. Contribute to open source security projects. Each script you write builds both skill and a portfolio that demonstrates capability to employers.
What to Build Next
Once you have the three scripts from this guide working, extend them. Add multi-threading to the port scanner so it finishes in seconds instead of minutes. Make the log analyzer accept command line arguments so it works with different log formats. Schedule the integrity checker to run hourly with cron and send email alerts when changes are detected.
Then tackle new projects. Write a script that queries the VirusTotal API to check file hashes against known malware signatures. Build a simple incident response toolkit that collects system information, active connections, running processes, and recent file changes into a single report. Create a password strength analyzer that checks passwords against common wordlists and calculates entropy.
Every script you build reinforces two skills simultaneously: Python programming and security thinking. You learn to think like both a defender and an attacker, which is exactly what employers want. The junior analyst who automated 847 log entries on a Friday evening became the team's go to person for automation within six months. Not because he was the best programmer, but because he was the analyst who could translate security problems into working solutions.
Start with the port scanner. Run it against your own machine. Read the output. Understand what each open port means. That is the first step from theory to practice, and Python is the bridge that gets you there.
Cybersecurity strategist with experience spanning international organizations, aviation security, and Security Operations Centers. Former threat analyst and offensive security specialist now focused on workforce development. Researches the intersection of AI anthropology and machine behaviour to shape next-generation security education.
View ProfileReady to Start Your Cybersecurity Career?
Join hundreds of professionals who've transitioned into cybersecurity with our hands-on bootcamp.

