Chapter 1: Python Refresher for Cyber Security
Refresh Python fundamentals, functions, file handling, and error handling required for security automation.
Scripts
Logs
Errors
Security
1.1 Chapter Overview
Python is one of the most useful programming languages for cyber security because it is simple, flexible and powerful. Security analysts use Python to read logs, scan files, automate repetitive checks, parse alerts, validate indicators of compromise and generate security reports.
This chapter refreshes the Python fundamentals needed before moving into cyber security automation. The focus is not general programming only, but using Python in a security analyst context.
1.2 Learning Objectives
- Review Python variables, data types and operators.
- Use conditions and loops for security checks.
- Create reusable functions for automation tasks.
- Read, write and analyze text files and log files.
- Handle errors using try-except blocks.
- Use lists and dictionaries for security data.
- Build simple cyber security automation scripts.
- Understand safe and ethical use of security scripts.
1.3 Python Variables and Data Types
Variables store information that a program can use. In cyber security, variables may store usernames, IP addresses, file paths, alert counts, port numbers or risk levels.
| Data Type | Use | Cyber Security Example |
|---|---|---|
| String | Text data | "192.168.1.10", "admin", "malware.exe" |
| Integer | Whole number | failed_login_count = 7 |
| Float | Decimal number | risk_score = 8.5 |
| Boolean | True or False | is_suspicious = True |
| List | Collection of values | blocked_ips = ["10.0.0.5", "10.0.0.9"] |
| Dictionary | Key-value data | {"user":"admin", "status":"locked"} |
Example: Store Security Alert Data
username = "admin"
source_ip = "192.168.1.50"
failed_logins = 6
risk_score = 8.7
is_suspicious = True
print("User:", username)
print("Source IP:", source_ip)
print("Failed Logins:", failed_logins)
print("Risk Score:", risk_score)
print("Suspicious:", is_suspicious)User: admin
Source IP: 192.168.1.50
Failed Logins: 6
Risk Score: 8.7
Suspicious: True
1.4 Lists and Dictionaries for Security Data
Security analysts often work with collections of IP addresses, usernames, domains, hashes and alerts.
List Example: Blocked IP Addresses
blocked_ips = ["192.168.1.10", "10.0.0.15", "172.16.5.20"]
new_ip = "10.0.0.15"
if new_ip in blocked_ips:
print("Alert: IP is already blocked")
else:
print("IP is not in block list")Dictionary Example: Security Event
event = {"username": "admin", "ip": "192.168.1.50", "event_type": "failed_login", "severity": "high"}
print("User:", event["username"])
print("IP Address:", event["ip"])
print("Severity:", event["severity"])1.5 Conditions and Loops
Conditions allow Python to make decisions. Loops help process many records automatically.
failed_logins = 8
if failed_logins >= 5:
print("High risk: too many failed login attempts")
else:
print("Login activity appears normal")Loop Through IP Addresses
ip_addresses = ["192.168.1.10", "10.0.0.5", "203.0.113.99"]
for ip in ip_addresses:
print("Checking IP:", ip)1.6 Functions for Reusable Security Automation
A function is a reusable block of code. Functions make scripts easier to read, test and maintain.
def check_failed_logins(username, failed_count):
if failed_count >= 5:
return username + " is suspicious"
else:
return username + " is normal"
result = check_failed_logins("admin", 7)
print(result)Function to Check IP Block List
def is_blocked(ip_address, blocked_list):
return ip_address in blocked_list
blocked_ips = ["10.0.0.5", "192.168.1.25"]
test_ip = "10.0.0.5"
if is_blocked(test_ip, blocked_ips):
print("Blocked IP detected:", test_ip)
else:
print("IP is allowed:", test_ip)1.7 File Handling for Security Logs
Security logs are often stored in text files, CSV files or JSON files. Python can read these files and search for suspicious entries.
Create a Sample Log File
log_data = """INFO User amin logged in
WARNING Failed login for admin
ERROR Multiple failed logins from 192.168.1.50
INFO User ravi logged out
"""
with open("security_log.txt", "w", encoding="utf-8") as file:
file.write(log_data)
print("Sample log file created.")Search for ERROR Lines
with open("security_log.txt", "r", encoding="utf-8") as file:
for line in file:
if "ERROR" in line:
print("Security Alert:", line.strip())1.8 CSV Alert Report
import csv
alerts = [
["Time", "User", "IP", "Severity"],
["10:01", "admin", "192.168.1.50", "High"],
["10:05", "guest", "10.0.0.20", "Low"]
]
with open("security_alerts.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(alerts)
print("Security alert CSV created.")import csv
with open("security_alerts.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
if row["Severity"] == "High":
print("High severity alert:", row["User"], row["IP"])1.9 Error Handling for Reliable Security Scripts
Security automation scripts must handle missing files, invalid input and unexpected data.
try:
with open("missing_log.txt", "r", encoding="utf-8") as file:
content = file.read()
except FileNotFoundError:
print("Error: Log file was not found.")try:
failed_logins = int(input("Enter failed login count: "))
if failed_logins >= 5:
print("Suspicious login activity")
else:
print("Normal login activity")
except ValueError:
print("Please enter a valid number.")1.10 Real Security Automation Examples
Detect Suspicious Login Attempts
login_events = [
{"user": "admin", "failed": 7, "ip": "192.168.1.50"},
{"user": "amin", "failed": 1, "ip": "10.0.0.10"},
{"user": "guest", "failed": 6, "ip": "203.0.113.5"}
]
for event in login_events:
if event["failed"] >= 5:
print("Suspicious login detected")
print("User:", event["user"])
print("IP:", event["ip"])
print("Failed Attempts:", event["failed"])
print("-" * 30)Simple Port Risk Checker
dangerous_ports = {21: "FTP", 23: "Telnet", 3389: "Remote Desktop"}
open_ports = [22, 80, 443, 3389]
for port in open_ports:
if port in dangerous_ports:
print("Risk: Port", port, dangerous_ports[port], "is open")
else:
print("Port", port, "appears acceptable")Password Strength Checker
def check_password_strength(password):
score = 0
if len(password) >= 8: score += 1
if any(char.isdigit() for char in password): score += 1
if any(char.isupper() for char in password): score += 1
if any(char in "!@#$%^&*" for char in password): score += 1
if score >= 3: return "Strong"
elif score == 2: return "Medium"
else: return "Weak"
print("Password Strength:", check_password_strength("Pdtc@2026"))1.11 Interactive Password Strength Demo
1.12 Safe and Ethical Use
| Allowed Practice | Not Allowed Practice |
|---|---|
| Analyze your own training log files. | Access someone else's private logs without permission. |
| Test scripts in a lab environment. | Run scripts against public systems without authorization. |
| Automate internal security reports. | Collect credentials or personal data illegally. |
1.13 Practical Activities
Activity 1: Block List Checker
Create a Python list of blocked IP addresses and check whether a new IP exists in the list.
Activity 2: Log Reader
Create a text log file and write a Python script that prints only lines containing ERROR or WARNING.
Activity 3: Password Checker
Create a function that classifies passwords as Weak, Medium or Strong.
Mini Project
Build a script that reads a log file, detects suspicious lines and writes a summary report.
1.14 Interactive Final Assessment Quiz
Each correct answer gives +1 mark. Each wrong answer gives -0.5 mark.
1. Python can be used for cyber security automation.
2. Which data type stores True or False?
3. A list can store multiple IP addresses.
4. Which keyword defines a function in Python?
5. File handling can be used to read security logs.
6. Which block handles errors in Python?
7. Failed login count can be used as a security indicator.
8. It is ethical to run security scripts on any public system without permission.
9. CSV files can store security alert reports.
10. A reusable password checker can be written as a Python function.
Your Score: 0
1.15 Chapter Summary
In this chapter, learners refreshed Python fundamentals required for cyber security automation. They reviewed variables, data types, conditions, loops, functions, file handling, CSV handling, error handling and simple security automation scripts.