Python Windows Automation Script Generator | Ornet 🐍

Python Windows Automation Script Generator 🐍

Turns everyday IT tasks into smart, reliable automation. Pick a use case from the GUI and get ready-to-run code with full setup and import instructions.

🚀 Step 0: Setting Up the Basic Work Environment (One-Time, Per Machine)

Open CMD as Administrator (Run as Administrator) and run this one-time command to install Python on the machine:
winget install Python.Python.3.11
1. Choose an Internal Automation Use Case

🏛️ Control Panel Shortcuts

Quick navigation and opening of deep settings screens (Network Connections, Firewall, System Properties).

🖥️ Hardware Inventory (WMI Inventory)

Pulls the serial number (S/N), manufacturer, model, and passes it on to a full inventory table.

🧩 System Cleanup

Automatic scanning and deletion of junk files and temporary folders in the local Temp directory.

🔒 Cyber Hardening

Checks active Defender antivirus status and confirms USB port-blocking policies.

📁 File Automation

Automatic scanning and archiving of a defined folder into a ZIP file organized by date or network path.

🌐 Local Subnet Scanner (Python NetScan CLI)

Scans IP addresses and MAC addresses on-site, mapping the operating system and open ports on the LAN.

📋 Setup Instructions & Ready-to-Run Code
📌 What Do You Need to Import for This Script?
Nothing outside the standard library — no extra installation needed!
🎯 What Does This Script Actually Do?
  • Choice 1: opens the Network Connections & IP Settings screen.
  • Choice 2: opens the "Add/Remove Programs" screen.
  • Choice 3: opens the System Properties & Windows Users screen.
  • Choice 4: opens the Windows Firewall screen.
import os
import sys

def open_shortcut(choice):
    shortcuts = {
        "1": "control ncpa.cpl",
        "2": "control appwiz.cpl",
        "3": "control sysdm.cpl",
        "4": "control firewall.cpl"
    }

    if choice in shortcuts:
        print(f"[+] Running local command: {shortcuts[choice]}")
        os.system(shortcuts[choice])
    else:
        print("[-] Invalid choice")

if __name__ == '__main__':
    print("--- Ornet IT Control Panel Shortcuts Tool ---")
    print("1 - Network Connections (ncpa.cpl)")
    print("2 - Add/Remove Programs (appwiz.cpl)")
    print("3 - System Properties (sysdm.cpl)")
    print("4 - Windows Firewall (firewall.cpl)")

    user_choice = input("\nSelect menu number: ")
    open_shortcut(user_choice)
📌 What Do You Need to Import for This Script?
🛑 Run this in CMD as Administrator before running the script: pip install WMI
🎯 What Does This Script Actually Do?
  • Connects to the local WMI (Windows Management Instrumentation) interface.
  • Pulls the computer's real Serial Number (S/N) from the BIOS.
  • Also retrieves manufacturer name, exact model, and passes it on to an inventory table.
import wmi
import sys

def get_hardware_info():
    print("[*] Gathering local hardware asset inventory via BIOS...")
    c = wmi.WMI()

    for bios in c.Win32_Bios():
        print(f"-> Computer Serial Number (S/N): {bios.SerialNumber.strip()}")

    for comp in c.Win32_ComputerSystem():
        print(f"-> Vendor: {comp.Manufacturer}")
        print(f"-> System Model: {comp.Model}")

    for cpu in c.Win32_Processor():
        print(f"-> CPU Architecture: {cpu.Name.strip()}")

if __name__ == '__main__':
    get_hardware_info()
    input("\nPress Enter to close window...")
📌 What Do You Need to Import for This Script?
Nothing outside the standard library — no extra installation needed!
🎯 What Does This Script Actually Do?
  • Automatically identifies the current user profile that runs the script on Windows.
  • Scans the local AppData Temp folder and clears out junk files and temporary folders.
  • Wraps every automatic delete operation in a Try-Except block that skips files locked by the system.
import os
import shutil
import getpass

def clean_temp():
    username = getpass.getuser()
    temp_path = f"C:\\Users\\{username}\\AppData\\Local\\Temp"

    print(f"[*] Scanning cache targets at: {temp_path}")
    deleted_files = 0
    deleted_folders = 0

    for item in os.listdir(temp_path):
        item_path = os.path.join(temp_path, item)
        try:
            if os.path.isfile(item_path) or os.path.islink(item_path):
                os.unlink(item_path)
                deleted_files += 1
            elif os.path.isdir(item_path):
                shutil.rmtree(item_path)
                deleted_folders += 1
        except Exception:
            continue

    print(f"[+] Cleanup pipeline finished.")
    print(f"-> Purged {deleted_files} system files.")
    print(f"-> Purged {deleted_folders} empty folders.")

if __name__ == '__main__':
    clean_temp()
    input("\nPress Enter to close window...")
📌 What Do You Need to Run in CMD as Administrator Before Importing & Running?
This script needs the WMI library to query Windows's security center. Copy and run these commands in CMD (as Administrator):
python -m pip install WMI --user --break-system-packages
python check_cyber_security_status.py
🎯 What Does This Script Actually Do?
  • Active Antivirus Detection (AV Detection): Queries Windows's SecurityCenter2 namespace and shows the exact name of the active endpoint security product (EDR/XDR/Antivirus) reporting to the system (e.g., SentinelOne, ESET, CrowdStrike, or Defender).
  • USB Port-Blocking Policy Check: Scans the Registry for the loading state of the USBSTOR driver to confirm whether removable media is blocked at the organization level, preventing data leakage or malicious drops (Rubber Ducky).
import os
import subprocess
import wmi
import sys

def get_active_antivirus():
    print("[*] Querying Windows SecurityCenter2 database for active protection...")
    try:
        w = wmi.WMI(namespace="root\\SecurityCenter2")
        antivirus_products = w.AntivirusProduct()

        if not antivirus_products:
            print("[-] ALERT: No registered Antivirus software found on this machine!")
            return

        for product in antivirus_products:
            name = product.displayName
            state = int(product.productState)
            is_active = (state & 0x1000) != 0

            status_str = "ACTIVE & RUNNING" if is_active else "DISABLED / SUSPENDED"
            print(f"[+] Found Security Product: '{name}' --> Status: [{status_str}]")
    except Exception as e:
        print(f"[-] Fallback: Direct WMI querying failed ({str(e)}). Checking local process tree...")
        try:
            tasks = subprocess.check_output('tasklist /FI "IMAGENAME eq MsMpEng.exe"', shell=True).decode('cp1255')
            if "MsMpEng.exe" in tasks:
                print("[+] Windows Defender Antivirus: Running in background daemon mode")
            else:
                print("[-] Unable to parse active antivirus software from memory.")
        except Exception:
            print("[-] Execution Error: Access to local Security Center provider was denied.")

def check_usb_blocking():
    print("\n[*] Auditing Local Registry Endpoint Hardening policies...")
    cmd = 'reg query "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR" /v Start'
    try:
        output = subprocess.check_output(cmd, shell=True).decode()
        if "0x4" in output:
            print("[+] USB Storage Hardware: BLOCKED via Group Policy / Registry (Secure)")
        else:
            print("[!] USB Interface State: OPEN. Removable thumb drives can be mounted.")
    except Exception:
        print("[!] Default USB configuration detected (No custom group policy)")

if __name__ == '__main__':
    print("--- Ornet Security Hardening Audit Tool ---")
    get_active_antivirus()
    check_usb_blocking()
    input("\nAudit complete. Press Enter to close window...")
📌 What Do You Need to Import for This Script?
Nothing outside the standard library — no extra installation needed!
🎯 What Does This Script Actually Do?
  • Performs a recursive scan (os.walk) over every file and folder in the target directory.
  • Packs every file into a single ZIP archive while preserving the original folder structure.
  • Generates a unique timestamp for the archive name to prevent overwriting older backups.
import os
import zipfile
from datetime import datetime

def backup_to_zip(source_dir, output_zip):
    print(f"[*] Initializing compression routine for target: {source_dir}")
    try:
        with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for root, dirs, files in os.walk(source_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    zipf.write(file_path, os.path.relpath(file_path, source_dir))
        print(f"[+] Archive compiled. Output file absolute path: {output_zip}")
    except Exception as e:
        print(f"[-] Execution fallback error: {str(e)}")

if __name__ == '__main__':
    source = "C:\\Ornet_Projects"
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    destination = f"C:\\Backup_Archive_{timestamp}.zip"

    if os.path.exists(source):
        backup_to_zip(source, destination)
    else:
        print(f"[-] Root directory data source [{source}] not found on this machine.")
    input("\nPress Enter to close window...")
📌 What Do You Need to Run in CMD as Administrator Before Importing & Running?
Copy and run these 3 commands in sequence inside CMD (as Administrator) to install the driver, the library, and then run the script:
winget install Nmap.Npcap --accept-source-agreements --accept-package-agreements
python -m pip install scapy --user --break-system-packages
python ornet_netscan.py
🎯 What Does This Script Actually Do?
  • Broadcast ARP Scan: Discovers every device alive on the local subnet (including devices that block Ping).
  • IP & MAC Extraction: Maps the internal LAN accurately and quickly.
  • OS Fingerprinting: Analyzes packet TTL values to determine whether a device is running Windows or Linux/Mac.
  • Port Scanning: Checks for open common ports such as 22 (SSH), 80/443 (Web), 445 (SMB), and 3389 (RDP).
import scapy.all as scapy
import socket
import sys

def get_os_fingerprint(ttl):
    if ttl <= 64:
        return "Linux / Linux-Based (Android/IoT/Mac)"
    elif ttl <= 128:
        return "Windows System (Client/Server)"
    else:
        return "Network Device / Cisco Infrastructure"

def scan_ports(ip):
    target_ports = [21, 22, 80, 443, 445, 3389]
    open_ports = []

    for port in target_ports:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(0.3)
        result = s.connect_ex((ip, port))
        if result == 0:
            open_ports.append(str(port))
        s.close()

    return ", ".join(open_ports) if open_ports else "None Detected"

def run_network_scanner(ip_range):
    print(f"[*] Initializing Ornet Advanced ARP Discovery Pipeline for: {ip_range}")
    print("[*] Sending layout requests. Please wait...\n")

    arp_request = scapy.ARP(pdst=ip_range)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_packet = broadcast / arp_request

    answered_list = scapy.srp(arp_request_packet, timeout=2, verbose=False)[0]

    print("-" * 85)
    print(f"{'IP ADDRESS':<16} {'MAC ADDRESS':<20} {'ESTIMATED OS':<30} {'OPEN PORTS'}")
    print("-" * 85)

    for element in answered_list:
        ip = element[1].psrc
        mac = element[1].hwsrc

        try:
            ping_packet = scapy.IP(dst=ip)/scapy.ICMP()
            ping_reply = scapy.sr1(ping_packet, timeout=0.5, verbose=False)
            if ping_reply:
                ttl_val = ping_reply.ttl
                os_guess = get_os_fingerprint(ttl_val)
            else:
                os_guess = "Unknown (ICMP Blocked)"
        except Exception:
            os_guess = "Unknown Profile"

        detected_ports = scan_ports(ip)
        print(f"{ip:<16} {mac:<20} {os_guess:<30} {detected_ports}")

if __name__ == '__main__':
    if len(sys.argv) > 1:
        target_subnet = sys.argv[1]
    else:
        target_subnet = input("Enter Target Local Subnet (e.g., 192.168.1.0/24): ")

    run_network_scanner(target_subnet)
    input("\nScan complete. Press Enter to exit...")
✍️

Hayim Caspy | Ornet Communications, Infrastructure & Security Systems

[email protected] | 03-570-5253
💡 טיפ טכנולוגי
אבטחת מידע לעסקים קרא עוד ←
🌐 עברית