Chapter 1: Python Refresher for Cyber Security

Refresh Python fundamentals, functions, file handling, and error handling required for security automation.

Python BasicsFunctionsFile HandlingError HandlingSecurity Automation
Write
Scripts
Read
Logs
Handle
Errors
Automate
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.

Learning Outcome: By the end of this chapter, learners should be able to write basic Python scripts, create functions, work with files, handle errors and apply Python to simple cyber security automation tasks.
1Python Basics
2Decision Logic
3Functions
4File Handling
5Security Automation

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 TypeUseCyber Security Example
StringText data"192.168.1.10", "admin", "malware.exe"
IntegerWhole numberfailed_login_count = 7
FloatDecimal numberrisk_score = 8.5
BooleanTrue or Falseis_suspicious = True
ListCollection of valuesblocked_ips = ["10.0.0.5", "10.0.0.9"]
DictionaryKey-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)
Expected Output:
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

Click Check Strength.

1.12 Safe and Ethical Use

Ethical Reminder: Use Python security scripts only on systems you own, manage or have written permission to test. Do not scan, access, attack or collect data from unauthorized systems.
Allowed PracticeNot 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.

Remember: Python is a powerful tool for defensive cyber security work when used ethically, safely and with proper authorization.