מחולל סקריפטים לאוטומציית Windows ב-Python | אורנט 🐍

מחולל סקריפטים לאוטומציית Windows ב-Python 🐍

הפוך משימות סיסטם ידניות לאוטומציה חכמה ותואמת ארגון. בחר נושא ב-GUI וקבל פקודות סנכרון והסברי אימפורט מלאים ללא שגיאות.

🚀 שלב 0: הכנת סביבת העבודה הבסיסית (חד-פעמי על המחשב)

פתחו חלון CMD כמנהל (Run as Administrator) והריצו את הפקודה הבאה להתקנה מהירה של פייתון על התחנה:
winget install Python.Python.3.11
1. בחר נושא לאוטומציה פנימית

🎛️ רכיבי לוח הבקרה (Control Panel)

ניווט מהיר והקפצת חלונות הגדרה עמוקים (כרטיס רשת, פיירוול, הסרת תוכנות).

🖥️ איסוף נתוני חומרה (WMI Inventory)

שליפת מספר סידורי (S/N), יצרן, דגם לוח אם ומעבד לטובת ניהול מלאי חכם.

🧹 תחזוקה וניקוי (System Cleanup)

סריקה ומחיקה אוטומטית של קבצי זבל ותיקיות זמניות בנתיבי Temp נעולים.

🔒 אבטחת מידע וסייבר (Cyber Hardening)

בדיקת סטטוס אנטי-וירוס Defender מובנה ואימות חסימות פורטים ורכיבי USB מקומיים.

📁 ניהול וגיבוי קבצים (File Automation)

ארכוב וגיבוי אוטומטי של תיקייה מוגדרת לקובץ ZIP מוצפן ביעד מקומי או ברשת.

🌐 סורק רשת מקומי מורחב (Python NetScan CLI)

סורק כתובות IP וכתובת MAC פנימיות, מזהה מערכות הפעלה וממפה פורטים פתוחים ב-LAN.

📋 פקודות התקנה וקוד מקור
📌 מה מתקינים בשביל ה-Import בסקריפט זה?
ספריה מובנית במערכת - אין צורך להתקין דבר חיצוני!
🎯 מה הסקריפט הזה מבצע בפועל?
  • בלחיצה על 1: פותח את ממשק כרטיסי הרשת והגדרות ה-IP.
  • בלחיצה על 2: פותח את חלון הסרת תוכנות מהמערכת.
  • בלחיצה על 3: פותח את משתני הסביבה ומאפייני הווינדוס.
  • בלחיצה על 4: פותח את חומת האש המקומית (Windows Firewall).
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)
📌 מה מתקינים בשביל ה-Import בסקריפט זה?
🛑 יש להריץ ב-CMD כמנהל לפני ההפעלה: pip install WMI
🎯 מה הסקריפט הזה מבצע בפועל?
  • מתחבר ישירות ל-WMI (Windows Management Instrumentation) המקומי.
  • שולף את ה-Serial Number (S/N) האמיתי של הלוח מה-BIOS.
  • מדפיס את שם היצרן, דגם המחשב המדויק וסוג המעבד לטובת Inventory.
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...")
📌 מה מתקינים בשביל ה-Import בסקריפט זה?
ספריה מובנית במערכת - אין צורך להתקין דבר חיצוני!
🎯 מה הסקריפט הזה מבצע בפועל?
  • מזהה אוטומטית את שם המשתמש הנוכחי שמריץ את התחנה בווינדוס.
  • סורק את תיקיית ה-AppData Temp המקומית ומנקה קבצים ותיקיות זבל.
  • כולל מנגנון Try-Except שמדלג אוטומטית על קבצים פתוחים שננעלו על ידי המערכת.
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...")
📌 מה מריצים ב-CMD כמנהל בשביל ה-Import וההפעלה?
הסקריפט דורש את ספריית ה-WMI כדי לתחקר את מרכז האבטחה של ווינדוס. העתיקו והדביקו את הפקודות הבאות ב-CMD (כמנהל מערכת):
python -m pip install WMI --user --break-system-packages
python check_cyber_security_status.py
🎯 מה הסקריפט הזה מבצע בפועל?
  • זיהוי אנטי-וירוס אקטיבי (AV Detection): מתשאל את ה-Namespace של SecurityCenter2 בווינדוס ומציג את השם המדויק של מוצר האבטחה הפעיל (EDR/XDR/Antivirus) המדווח למערכת (כמו SentinelOne, ESET, CrowdStrike או Defender).
  • בדיקת חסימת התקני USB: סורק את ה-Registry של תחנת הקצה ומאמת האם שירות USBSTOR חסום בארגון למניעת זליגת מידע או החדרת קבצים זדוניים (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...")
📌 מה מתקינים בשביל ה-Import בסקריפט זה?
ספריה מובנית במערכת - אין צורך להתקין דבר חיצוני!
🎯 מה הסקריפט הזה מבצע בפועל?
  • מבצע סריקה רקורסיבית (os.walk) על כל עץ התיקיות שמוגדר במקור.
  • דוחס את כל הקבצים לקובץ ארכיון ZIP יחיד תוך שמירה על מבנה התיקיות המקורי.
  • מייצר חותמת זמן (Timestamp) ייחודית לשם הקובץ למניעת דריסה של גיבויים ישנים.
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...")
📌 מה מריצים ב-CMD כמנהל בשביל ה-Import וההפעלה?
העתיקו והדביקו את 3 הפקודות הבאות ברצף בתוך חלון ה-CMD (כמנהל מערכת) כדי להתקין את הדרייבר, את הספרייה ולהריץ את הסקריפט בשנייה אחת:
winget install Nmap.Npcap --accept-source-agreements --accept-package-agreements
python -m pip install scapy --user --break-system-packages
python ornet_netscan.py
🎯 מה הסקריפט הזה מבצע בפועל?
  • סריקת ARP רוחבית: מגלה את כל המכשירים החיים ב-Subnet המקומי (מזהה גם מכשירים שחוסמים פינג).
  • חילוץ IP ו-MAC: ממפה בצורה מדויקת את רשת ה-LAN הארגונית.
  • אומדן מערכת הפעלה (OS Fingerprinting): מנתח את ערכי ה-TTL של הפקטים כדי לקבוע אם המכשיר מבוסס Windows או Linux/Mac.
  • סריקת פורטים: בודק פתיחת פורטי ניהול רגישים כמו 22 (SSH), 80/443 (Web), 445 (SMB) ו-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...")
✍️

חיים כספי | ארכיטקטורת תשתיות ומערכות אבטחה

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