Task Automation

Stop doing repetitive tasks. Let Python handle the boring stuff.

1. File Organization Script

This script automatically sorts files in a folder into subfolders based on their file extension (e.g., images go to /Images, PDFs go to /Documents).

import os
import shutil

def organize_folder(folder_path):
    # Define file types and their target folders
    extensions = {
        'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
        'Documents': ['.pdf', '.docx', '.txt', '.xlsx'],
        'Videos': ['.mp4', '.mkv', '.avi'],
        'Archives': ['.zip', '.rar', '.7z']
    }

    # Loop through all files in the directory
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        
        # Skip if it's a folder
        if os.path.isdir(file_path):
            continue

        # Get file extension
        _, ext = os.path.splitext(filename)
        ext = ext.lower()

        # Find which folder it belongs to
        moved = False
        for folder_name, ext_list in extensions.items():
            if ext in ext_list:
                target_dir = os.path.join(folder_path, folder_name)
                
                # Create folder if it doesn't exist
                if not os.path.exists(target_dir):
                    os.makedirs(target_dir)
                
                # Move the file
                shutil.move(file_path, os.path.join(target_dir, filename))
                print(f"Moved: {filename} -> {folder_name}/")
                moved = True
                break
        
        if not moved:
            print(f"Skipped: {filename} (Unknown type)")

# Usage:
# organize_folder("/path/to/your/messy/folder")

2. Web Scraping (Fetching Data)

Using requests and BeautifulSoup to extract data from a website. (Requires: pip install requests beautifulsoup4)

import requests
from bs4 import BeautifulSoup

def get_headlines(url):
    # Fetch the webpage
    response = requests.get(url)
    
    # Check if successful
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Find all <h2> tags (change this based on the site)
        headlines = soup.find_all('h2')
        
        for i, headline in enumerate(headlines, 1):
            print(f"{i}. {headline.text.strip()}")
    else:
        print("Failed to fetch page.")

# Usage:
# get_headlines("https://news.ycombinator.com/")

Network Defense

Protect infrastructure. Understand how data flows and how to secure it.

1. Port Scanner (Defensive Check)

Before attackers find your open ports, find them yourself. This basic script checks if specific ports are open on a server.

import socket
import sys

def scan_ports(target, ports):
    print(f"Scanning Target: {target}")
    
    for port in ports:
        # Create a socket object
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        
        # Set a timeout (don't wait forever)
        s.settimeout(1.0)
        
        # Attempt connection
        result = s.connect_ex((target, port))
        
        if result == 0:
            print(f"[+] Port {port} is OPEN")
        else:
            print(f"[-] Port {port} is CLOSED")
        
        s.close()

# Usage: Scanning common ports on localhost
# scan_ports("127.0.0.1", [21, 22, 80, 443, 3306])

// HOW FIREWALLS WORK

A firewall acts as a barrier between a trusted network (your internal system) and an untrusted network (the internet). It examines incoming and outgoing traffic based on predefined security rules.

  • Allow Rules: Traffic that is permitted (e.g., Port 80 for web).
  • Deny Rules: Traffic that is blocked (e.g., Blocking SSH on public IPs).

Offensive Security

Think like an attacker to build better defenses.

⚠️ ETHICAL DISCLAIMER

The techniques and code shown here are strictly for educational purposes and authorized penetration testing. Never test these on systems you do not own or have explicit permission to test. Unauthorized hacking is illegal.

1. HTTP Header Grabber

Gathering HTTP headers is part of reconnaissance. It can reveal what server software is running, which can help attackers (or defenders) identify potential vulnerabilities.

import requests

def get_headers(url):
    try:
        response = requests.get(url, timeout=5)
        print(f"Headers for {url}:\n")
        
        for header, value in response.headers.items():
            print(f"{header}: {value}")
            
    except Exception as e:
        print(f"Error: {e}")

# Usage:
# get_headers("https://example.com")

2. Basic Brute-Force Logic (Simulation)

Understanding how brute-force attacks work is crucial for defense. This is a simulated loop (it does not actually connect to a server).

import string
import time

def simulate_bruteforce(target_password, max_length=3):
    chars = string.ascii_lowercase
    attempts = 0
    start_time = time.time()
    
    print("Starting simulation...")
    
    # This generates combinations (AAA, AAB, AAC, etc.)
    for length in range(1, max_length + 1):
        for combination in itertools.product(chars, repeat=length):
            attempt = ''.join(combination)
            attempts += 1
            
            if attempt == target_password:
                end_time = time.time()
                print(f"Password found: {attempt}")
                print(f"Attempts: {attempts}")
                print(f"Time: {end_time - start_time:.2f} seconds")
                return
    
    print("Password not found.")

# Usage:
# simulate_bruteforce("abc")

Cryptography

The mathematics of secrecy and integrity.

1. Hashing Passwords (SHA-256)

Never store passwords in plaintext. Hashing is a one-way function. You can turn a password into a hash, but you cannot turn the hash back into the password.

import hashlib

def hash_password(password):
    # Encode the password to bytes
    encoded_pw = password.encode('utf-8')
    
    # Create a SHA-256 hash object
    hash_obj = hashlib.sha256(encoded_pw)
    
    # Get the hexadecimal representation
    hex_digest = hash_obj.hexdigest()
    return hex_digest

# Usage:
# print(hash_password("mySuperSecretPassword123"))
# Output: a03b8... (always 64 characters long)

2. Symmetric Encryption (Fernet)

Symmetric means the same key is used to lock and unlock the data. (Requires: pip install cryptography)

from cryptography.fernet import Fernet

# 1. Generate a key (Do this once and SAVE IT securely!)
# key = Fernet.generate_key()
# print(key)

# 2. Use the key to encrypt/decrypt
key = b'YOUR_SAVED_KEY_HERE'
cipher = Fernet(key)

def encrypt_message(message):
    encoded_msg = message.encode()
    encrypted = cipher.encrypt(encoded_msg)
    return encrypted

def decrypt_message(encrypted_msg):
    decrypted = cipher.decrypt(encrypted_msg)
    return decrypted.decode()

# Usage:
# encrypted = encrypt_message("Secret plans")
# print("Encrypted:", encrypted)
# print("Decrypted:", decrypt_message(encrypted))

OSINT & Recon

Open Source Intelligence. Information is power.

1. IP Geolocation Lookup

Use public APIs to find out where an IP address is located. This uses the free ip-api.com service.

import requests

def ip_lookup(ip_address):
    # Free API endpoint
    url = f"http://ip-api.com/json/{ip_address}"
    
    try:
        response = requests.get(url)
        data = response.json()
        
        if data['status'] == 'success':
            print(f"--- Info for {ip_address} ---")
            print(f"Country: {data['country']}")
            print(f"City: {data['city']}")
            print(f"ISP: {data['isp']}")
            print(f"Lat/Lon: {data['lat']}, {data['lon']}")
        else:
            print("IP not found or invalid.")
            
    except Exception as e:
        print(f"Error: {e}")

# Usage:
# ip_lookup("8.8.8.8") # Google's Public DNS

2. Domain WHOIS Lookup

Find out who registered a domain, when it was created, and when it expires. (Requires: pip install python-whois)

import whois

def get_domain_info(domain):
    try:
        w = whois.whois(domain)
        
        print(f"--- WHOIS for {domain} ---")
        print(f"Registrar: {w.registrar}")
        print(f"Creation Date: {w.creation_date}")
        print(f"Expiration Date: {w.expiration_date}")
        print(f"Name Servers: {w.name_servers}")
        print(f"Emails: {w.emails}")
        
    except Exception as e:
        print(f"Error: {e}")

# Usage:
# get_domain_info("github.com")