Automate Security Tasks Using Python Scripts

Business Scenario

Welcome!
You are working as a cybersecurity analyst at our company.

 

A company wants to strengthen its cybersecurity infrastructure by enforcing strong password policies, automating log monitoring to detect cyber threats in real time, and auditing systems to identify insecure files, weak configurations, and sensitive data exposure.

Pre-Lab Preparation

You are tasked with :-

  • To develop and manage these automated security

  • Monitoring processes using Python.

Topic :  Networking and Security Scripting with Python

1) Socket programming basics

2) Writing scripts for automation

3) Automating simple security tasks

Task 1: Password Strength Checking System (Enterprise Level)

In this lab, you will build an enterprise-level password strength checking system using Python. You will learn how to validate passwords based on security rules such as length, uppercase and lowercase letters, numbers, and special characters. You will also understand how organizations enforce strong password policies to improve account security and reduce the risk of cyberattacks like brute-force and password guessing attacks.

Program :

import re
import os

# ---------------- PASSWORD CHECK ----------------

def password_strength(password):
    score = 0
    feedback = []

    if len(password) >= 8:
        score += 1
    else:
        feedback.append("Min 8 chars")

    if re.search("[A-Z]", password):
        score += 1
    else:
        feedback.append("Add uppercase")

    if re.search("[a-z]", password):
        score += 1
    else:
        feedback.append("Add lowercase")

    if re.search("[0-9]", password):
        score += 1
    else:
        feedback.append("Add number")

    if re.search("[@#$%^&+=]", password):
        score += 1
    else:
        feedback.append("Add special char")

    if score == 5:
        return "Very Strong", feedback
    elif score >= 3:
        return "Moderate", feedback
    else:
        return "Weak", feedback


# ---------------- AUTOMATION ----------------
def automated_check(input_file, output_file):
    
    if not os.path.exists(input_file):
        print("Input file not found!")
        return

    with open(input_file, "r") as f:
        passwords = f.readlines()

    with open(output_file, "w") as report:
        report.write("PASSWORD SECURITY REPORT\n")
        report.write("="*40 + "\n")

        for pwd in passwords:
            pwd = pwd.strip()
            status, feedback = password_strength(pwd)

            report.write(f"\nPassword: {pwd}\n")
            report.write(f"Strength: {status}\n")

            if feedback:
                report.write("Suggestions: " + ", ".join(feedback) + "\n")

    print("Automation Complete! Report saved in", output_file)


# ---------------- MAIN ----------------
if __name__ == "__main__":
    automated_check("passwords.txt", "report.txt")
________________________________________
import re
import os

# ---------------- PASSWORD CHECK ----------------

def password_strength(password):
    score = 0
    feedback = []

    if len(password) >= 8:
        score += 1
    else:
        feedback.append("Min 8 chars")

    if re.search("[A-Z]", password):
        score += 1
    else:
        feedback.append("Add uppercase")

    if re.search("[a-z]", password):
        score += 1
    else:
        feedback.append("Add lowercase")

    if re.search("[0-9]", password):
        score += 1
    else:
        feedback.append("Add number")

    if re.search("[@#$%^&+=]", password):
        score += 1
    else:
        feedback.append("Add special char")

    if score == 5:
        return "Very Strong", feedback
    elif score >= 3:
        return "Moderate", feedback
    else:
        return "Weak", feedback


# ---------------- AUTOMATION ----------------
def automated_check(input_file, output_file):
    
    if not os.path.exists(input_file):
        print("Input file not found!")
        return

    with open(input_file, "r") as f:
        passwords = f.readlines()

    with open(output_file, "w") as report:
        report.write("PASSWORD SECURITY REPORT\n")
        report.write("="*40 + "\n")

        for pwd in passwords:
            pwd = pwd.strip()
            status, feedback = password_strength(pwd)

            report.write(f"\nPassword: {pwd}\n")
            report.write(f"Strength: {status}\n")

            if feedback:
                report.write("Suggestions: " + ", ".join(feedback) + "\n")

    print("Automation Complete! Report saved in", output_file)


# ---------------- MAIN ----------------
if __name__ == "__main__":
    automated_check("passwords.txt", "report.txt")
________________________________________
import re
import os

# ---------------- PASSWORD CHECK ----------------

def password_strength(password):
    score = 0
    feedback = []

    if len(password) >= 8:
        score += 1
    else:
        feedback.append("Min 8 chars")

    if re.search("[A-Z]", password):
        score += 1
    else:
        feedback.append("Add uppercase")

    if re.search("[a-z]", password):
        score += 1
    else:
        feedback.append("Add lowercase")

    if re.search("[0-9]", password):
        score += 1
    else:
        feedback.append("Add number")

    if re.search("[@#$%^&+=]", password):
        score += 1
    else:
        feedback.append("Add special char")

    if score == 5:
        return "Very Strong", feedback
    elif score >= 3:
        return "Moderate", feedback
    else:
        return "Weak", feedback


# ---------------- AUTOMATION ----------------
def automated_check(input_file, output_file):
    
    if not os.path.exists(input_file):
        print("Input file not found!")
        return

    with open(input_file, "r") as f:
        passwords = f.readlines()

    with open(output_file, "w") as report:
        report.write("PASSWORD SECURITY REPORT\n")
        report.write("="*40 + "\n")

        for pwd in passwords:
            pwd = pwd.strip()
            status, feedback = password_strength(pwd)

            report.write(f"\nPassword: {pwd}\n")
            report.write(f"Strength: {status}\n")

            if feedback:
                report.write("Suggestions: " + ", ".join(feedback) + "\n")

    print("Automation Complete! Report saved in", output_file)


# ---------------- MAIN ----------------
if __name__ == "__main__":
    automated_check("passwords.txt", "report.txt")

Password text file :

Output :

Report text file :

Task 2: File / Log Scanning System

In this lab, you will build a file and log scanning system using Python to monitor system activity.You will learn how to scan log files, detect suspicious patterns, and identify insecure or sensitive files.

This will help you understand how automated monitoring is used in real-world cybersecurity operations.

Program :

import os

def scan_log_file(file):
   keywords = ["failed login", "error", "unauthorized", "attack", "denied"]
   results = []

   if not os.path.exists(file):
       print("Log file not found!")
       return

   with open(file, "r") as f:
       for line_no, line in enumerate(f, start=1):
           for key in keywords:
               if key in line.lower():
                   results.append((line_no, line.strip()))

   return results


def analyze_logs(file):
   results = scan_log_file(file)

   if not results:
       print("No suspicious activity found.")
       return

   print("\n--- Suspicious Log Entries ---")
   for line_no, text in results:
       print(f"[Line {line_no}] {text}")

   print("\nTotal Alerts:", len(results))

# Example
if __name__ == "__main__":
   analyze_logs("system.log")
import os

def scan_log_file(file):
   keywords = ["failed login", "error", "unauthorized", "attack", "denied"]
   results = []

   if not os.path.exists(file):
       print("Log file not found!")
       return

   with open(file, "r") as f:
       for line_no, line in enumerate(f, start=1):
           for key in keywords:
               if key in line.lower():
                   results.append((line_no, line.strip()))

   return results


def analyze_logs(file):
   results = scan_log_file(file)

   if not results:
       print("No suspicious activity found.")
       return

   print("\n--- Suspicious Log Entries ---")
   for line_no, text in results:
       print(f"[Line {line_no}] {text}")

   print("\nTotal Alerts:", len(results))

# Example
if __name__ == "__main__":
   analyze_logs("system.log")

Log file used system.log :

Output :

Task 3: Vulnerability Scanning System (File-Based)

In this lab, you will build a file-based vulnerability scanning system using Python to identify security weaknesses in files and system configurations.You will learn how to detect insecure settings, sensitive data exposure, and potentially risky files.

This will help you understand how vulnerability assessment is performed in real-world cybersecurity environments.

Program :

import os

def scan_vulnerabilities(directory):
   issues = []

   if not os.path.exists(directory):
       print("Directory not found!")
       return

   for root, dirs, files in os.walk(directory):
       for file in files:
           path = os.path.join(root, file)

           # 1. Sensitive file names
           if "password" in file.lower() or "secret" in file.lower():
               issues.append(f"Sensitive file: {path}")

           # 2. Large files (possible log overflow)
           if os.path.getsize(path) > 10000:
               issues.append(f"Large file: {path}")

           # 3. Empty files
           if os.path.getsize(path) == 0:
               issues.append(f"Empty file: {path}")

           # 4. Executable files (risk)
           if file.endswith(".exe") or file.endswith(".sh"):
               issues.append(f"Executable file found: {path}")

   return issues


def report(directory):
   results = scan_vulnerabilities(directory)

   print("\n--- Vulnerability Report ---")

   if not results:
       print("No vulnerabilities found.")
   else:
       for issue in results:
           print(issue)

       print("\nTotal Issues Found:", len(results))


# Example
if __name__ == "__main__":
   report(".")
import os

def scan_vulnerabilities(directory):
   issues = []

   if not os.path.exists(directory):
       print("Directory not found!")
       return

   for root, dirs, files in os.walk(directory):
       for file in files:
           path = os.path.join(root, file)

           # 1. Sensitive file names
           if "password" in file.lower() or "secret" in file.lower():
               issues.append(f"Sensitive file: {path}")

           # 2. Large files (possible log overflow)
           if os.path.getsize(path) > 10000:
               issues.append(f"Large file: {path}")

           # 3. Empty files
           if os.path.getsize(path) == 0:
               issues.append(f"Empty file: {path}")

           # 4. Executable files (risk)
           if file.endswith(".exe") or file.endswith(".sh"):
               issues.append(f"Executable file found: {path}")

   return issues


def report(directory):
   results = scan_vulnerabilities(directory)

   print("\n--- Vulnerability Report ---")

   if not results:
       print("No vulnerabilities found.")
   else:
       for issue in results:
           print(issue)

       print("\nTotal Issues Found:", len(results))


# Example
if __name__ == "__main__":
   report(".")
import os

def scan_vulnerabilities(directory):
   issues = []

   if not os.path.exists(directory):
       print("Directory not found!")
       return

   for root, dirs, files in os.walk(directory):
       for file in files:
           path = os.path.join(root, file)

           # 1. Sensitive file names
           if "password" in file.lower() or "secret" in file.lower():
               issues.append(f"Sensitive file: {path}")

           # 2. Large files (possible log overflow)
           if os.path.getsize(path) > 10000:
               issues.append(f"Large file: {path}")

           # 3. Empty files
           if os.path.getsize(path) == 0:
               issues.append(f"Empty file: {path}")

           # 4. Executable files (risk)
           if file.endswith(".exe") or file.endswith(".sh"):
               issues.append(f"Executable file found: {path}")

   return issues


def report(directory):
   results = scan_vulnerabilities(directory)

   print("\n--- Vulnerability Report ---")

   if not results:
       print("No vulnerabilities found.")
   else:
       for issue in results:
           print(issue)

       print("\nTotal Issues Found:", len(results))

# Example
if __name__ == "__main__":
   report(".")

Output :

 

Great job!
You have successfully completed your lab on
Automate Security Tasks Using Python Scripts

In this lab, you have implemented a Password Strength Checking System, developed a File and Log Scanning System, and built a Vulnerability Scanning System to identify security weaknesses and monitor system activity using Python.

You are now ready to move to the next stage of cybersecurity training.

Checkpoint

Next Lab Preparation

Topic :  Practical Cybersecurity Projects Using Python

1) Building a simple port scanner

2) Log analysis using Python scripts

P7 :- Automate Security Tasks Using Python Scripts

By Content ITV

P7 :- Automate Security Tasks Using Python Scripts

  • 10