Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- NAJEEB TOTAL CMD COMMANDS V7.2 ULTIMATE - PATH EXECUTOR EDITION
- ✅ Fixed: Initialization Order Error
- ✅ Features: Edit Before Run | Copy | Browse Path | Execute from Any Directory
- ✅ Compatible: Windows 7 32-bit | Python 3.7.9 | BY NAJEEB SHAH KHAN
- """
- import tkinter as tk
- from tkinter import ttk, messagebox, simpledialog, filedialog
- import subprocess
- import os
- import json
- import threading
- import ctypes
- import time
- import queue
- import sys
- # Try import pyperclip for clipboard (optional fallback included)
- try:
- import pyperclip
- HAS_PYPERCLIP = True
- except ImportError:
- HAS_PYPERCLIP = False
- # 🔧 ADD THIS HERE 👇
- SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
- os.chdir(SCRIPT_DIR)
- print(f"[✅ FIXED] Script running from: {SCRIPT_DIR}")
- # --- Configuration ---
- FILE_NAME = "TOTAL-COMMANDS.db"
- FAV_FILE = "TOTAL-COMMANDS.json"
- CONFIG_FILE = "TOTAL-COMMANDS-CONFIG.json"
- VERSION = "7.2-FIXED"
- # --- Safety List (Dangerous Commands) ---
- DANGEROUS_KEYWORDS = ["format", "del /s", "rmdir /s", "fdisk", "diskpart", "shutdown /r"]
- # --- Quick Access Paths ---
- QUICK_PATHS = {
- "C:": "C:\\",
- "D:": "D:\\",
- "Desktop": os.path.join(os.path.expanduser("~"), "Desktop"),
- "Documents": os.path.join(os.path.expanduser("~"), "Documents"),
- "Downloads": os.path.join(os.path.expanduser("~"), "Downloads"),
- "Temp": os.getenv("TEMP", "C:\\Windows\\Temp"),
- "System32": "C:\\Windows\\System32",
- "Program Files": "C:\\Program Files",
- }
- # ============================================================================
- # ✅ ALL HELPER FUNCTIONS DEFINED FIRST (Before Class)
- # ============================================================================
- def safe_clipboard_copy(text, root=None):
- """Safely copy text to clipboard with fallback"""
- if HAS_PYPERCLIP:
- try:
- pyperclip.copy(text)
- return True
- except:
- pass
- if root:
- try:
- root.clipboard_clear()
- root.clipboard_append(text)
- root.update()
- return True
- except:
- pass
- return False
- def validate_directory(path):
- """Check if path is a valid directory"""
- try:
- return os.path.isdir(path)
- except:
- return False
- # ============================================================================
- # ✅ MAIN CLASS - METHODS IN LOGICAL ORDER
- # ============================================================================
- class GodModeV7:
- # ==================== INITIALIZATION ====================
- def __init__(self, root):
- self.root = root
- self.root.title(f"NAJEEB CMD COMMANDS RUNNER PRO MAX V{VERSION} | WIN7-32BIT-OPTIMIZED")
- self.root.geometry("1250x750")
- self.root.configure(bg="#1e1e1e")
- # Thread Safety Queue
- self.log_queue = queue.Queue()
- # Data Structures
- self.commands = {}
- self.favorites = set()
- self.config = {"geometry": "1250x750", "theme": "dark", "work_dir": ""}
- # Working Directory
- #self.work_dir = tk.StringVar(value=os.getcwd())
- self.work_dir = tk.StringVar(value=SCRIPT_DIR)
- # UI Elements (Initialize as None)
- self.cat_listbox = None
- self.cmd_listbox = None
- self.console = None
- self.notebook = None
- self.path_entry = None
- self.path_executor_entry = None
- self.executor_cmd = None
- self.executor_path_lbl = None
- self.file_listbox = None
- self.context_menu = None
- self.search_var = None
- self.path_var = None
- self.path_status = None
- self.status_var = None
- self.sys_info_text = None
- self.cpu_lbl = None
- self.ram_lbl = None
- self.proc_list = None
- # Load Config & Favorites FIRST (No UI needed)
- self.load_config()
- self.load_favorites()
- # Create UI SECOND
- self.create_main_layout()
- self.create_menu()
- # Load Commands THIRD (Now UI exists)
- self.load_commands()
- # Start Monitor Loop
- self.update_monitor()
- self.process_log_queue()
- # Handle Close
- self.root.protocol("WM_DELETE_WINDOW", self.on_close)
- # Log startup
- self.log(f"NAJEEB CLI PRO MAX V{VERSION} Started!\n")
- # ==================== UI CREATION ====================
- def create_main_layout(self):
- """Create main notebook and tabs"""
- self.notebook = ttk.Notebook(self.root)
- self.notebook.pack(fill="both", expand=True, padx=5, pady=5)
- # Tab 1: Command Center
- self.tab_cmd = tk.Frame(self.notebook, bg="#1e1e1e")
- self.notebook.add(self.tab_cmd, text="🚀 Command Center")
- self.setup_command_tab()
- # Tab 2: System & Network
- self.tab_sys = tk.Frame(self.notebook, bg="#1e1e1e")
- self.notebook.add(self.tab_sys, text="🖥️ System & Network")
- self.setup_system_tab()
- # Tab 3: Process Manager
- self.tab_proc = tk.Frame(self.notebook, bg="#1e1e1e")
- self.notebook.add(self.tab_proc, text="⚙️ Process Manager")
- self.setup_process_tab()
- # Tab 4: Path Executor (NEW!)
- self.tab_path = tk.Frame(self.notebook, bg="#1e1e1e")
- self.notebook.add(self.tab_path, text="📁 Path Executor")
- self.setup_path_tab()
- def setup_command_tab(self):
- """Setup Command Center tab with path selector"""
- # === PATH SELECTOR BAR ===
- path_frame = tk.Frame(self.tab_cmd, bg="#252526")
- path_frame.pack(fill="x", padx=5, pady=3)
- tk.Label(path_frame, text="📍 Work Dir:", bg="#252526", fg="#00ff00", font=("Consolas", 9)).pack(side="left", padx=5)
- self.path_entry = tk.Entry(path_frame, textvariable=self.work_dir, width=60, bg="#333", fg="white", insertbackground="white", font=("Consolas", 9))
- self.path_entry.pack(side="left", padx=5)
- self.path_entry.bind("<Return>", lambda e: self.validate_path())
- btn_browse = tk.Button(path_frame, text="🗂️ Browse", command=self.browse_path,
- bg="#007acc", fg="white", relief="flat", padx=8, pady=2, cursor="hand2")
- btn_browse.pack(side="left", padx=2)
- self.path_var = tk.StringVar(value="Quick Paths ▼")
- path_menu = tk.OptionMenu(path_frame, self.path_var, "Quick Paths ▼", *list(QUICK_PATHS.keys()), command=self.set_quick_path)
- path_menu.config(bg="#2d2d2d", fg="white", activebackground="#007acc", activeforeground="white", relief="flat", cursor="hand2")
- path_menu.pack(side="left", padx=5)
- tk.Button(path_frame, text="🔄 Reset", command=self.reset_path,
- bg="#555", fg="white", relief="flat", padx=8, pady=2, cursor="hand2").pack(side="left", padx=2)
- self.path_status = tk.Label(path_frame, text="✓ Valid", fg="lime", bg="#252526", font=("Consolas", 8))
- self.path_status.pack(side="right", padx=10)
- # === TOP FRAME (Search & Actions) ===
- top_frame = tk.Frame(self.tab_cmd, bg="#2d2d2d")
- top_frame.pack(fill="x", padx=5, pady=5)
- self.search_var = tk.StringVar()
- # ✅ FIX: Use lambda to avoid early binding issues
- self.search_var.trace_add("write", lambda *args: self.search_command())
- tk.Entry(top_frame, textvariable=self.search_var, width=40, bg="#333", fg="white", insertbackground="white").pack(side="left", padx=5)
- btn_style = {"bg": "#007acc", "fg": "white", "relief": "flat", "padx": 10, "pady": 5, "cursor": "hand2"}
- tk.Button(top_frame, text="▶ Run", command=self.run_selected, **btn_style).pack(side="left", padx=2)
- tk.Button(top_frame, text="✏️ Edit+Run", command=self.edit_and_run, **btn_style).pack(side="left", padx=2)
- tk.Button(top_frame, text="⚡ Admin", command=self.run_admin_selected, **btn_style).pack(side="left", padx=2)
- tk.Button(top_frame, text="⭐ Fav", command=self.toggle_fav, **btn_style).pack(side="left", padx=2)
- tk.Button(top_frame, text="➕ Add", command=self.add_command, **btn_style).pack(side="left", padx=2)
- tk.Button(top_frame, text="🗑️ Del", command=self.delete_command, **btn_style).pack(side="left", padx=2)
- tk.Button(top_frame, text="📋 Batch", command=self.run_batch, **btn_style).pack(side="left", padx=2)
- # === MIDDLE SPLIT (Categories & List) ===
- mid_pane = tk.PanedWindow(self.tab_cmd, orient="horizontal", bg="#1e1e1e")
- mid_pane.pack(fill="both", expand=True, padx=5, pady=5)
- # Left: Categories
- self.cat_listbox = tk.Listbox(mid_pane, bg="#252526", fg="#00ff00", selectbackground="#007acc", selectforeground="white", cursor="hand2")
- mid_pane.add(self.cat_listbox, width=200)
- self.cat_listbox.bind("<<ListboxSelect>>", self.on_category_select)
- # Right: Commands List
- self.cmd_listbox = tk.Listbox(mid_pane, bg="#1e1e1e", fg="white", selectbackground="#007acc", selectforeground="white", font=("Consolas", 10), exportselection=False)
- mid_pane.add(self.cmd_listbox)
- self.cmd_listbox.bind("<Double-Button-1>", lambda e: self.edit_and_run())
- self.cmd_listbox.bind("<Control-Button-1>", self.multi_select)
- self.cmd_listbox.bind("<Button-3>", self.show_context_menu)
- # Context Menu
- self._create_context_menu()
- # === BOTTOM: Console ===
- console_frame = tk.Frame(self.tab_cmd, bg="black")
- console_frame.pack(fill="x", padx=5, pady=5)
- self.console = tk.Text(console_frame, height=10, bg="black", fg="#00ff00", font=("Consolas", 9))
- self.console.pack(side="left", fill="both", expand=True)
- scroll = tk.Scrollbar(console_frame, command=self.console.yview)
- scroll.pack(side="right", fill="y")
- self.console.config(yscrollcommand=scroll.set)
- con_ctrl = tk.Frame(self.tab_cmd, bg="#1e1e1e")
- con_ctrl.pack(fill="x", padx=5)
- tk.Button(con_ctrl, text="Clear Log", command=lambda: self.console.delete(1.0, tk.END), cursor="hand2").pack(side="left")
- tk.Button(con_ctrl, text="Save Log", command=self.save_log, cursor="hand2").pack(side="left", padx=5)
- tk.Button(con_ctrl, text="📋 Copy Log", command=self.copy_console, cursor="hand2").pack(side="left", padx=5)
- # Status Bar
- self.status_var = tk.StringVar()
- self.status_var.set("Ready | Work Dir: " + self.work_dir.get()[:40] + "...")
- tk.Label(self.tab_cmd, textvariable=self.status_var, bg="#007acc", fg="white", anchor="w").pack(fill="x", side="bottom")
- def _create_context_menu(self):
- """Create right-click context menu for command list"""
- self.context_menu = tk.Menu(self.root, tearoff=0, bg="#2d2d2d", fg="white", activebackground="#007acc", activeforeground="white")
- self.context_menu.add_command(label="✏️ Edit Command", command=self.edit_selected_command)
- self.context_menu.add_command(label="📋 Copy to Clipboard", command=self.copy_selected_command)
- self.context_menu.add_separator()
- self.context_menu.add_command(label="▶ Run Normal", command=self.run_selected)
- self.context_menu.add_command(label="⚡ Run as Admin", command=self.run_admin_selected)
- self.context_menu.add_separator()
- self.context_menu.add_command(label="⭐ Toggle Favorite", command=self.toggle_fav)
- self.context_menu.add_command(label="🗑️ Delete Command", command=self.delete_command)
- def setup_path_tab(self):
- """Setup Path Executor tab"""
- # Path Input Section
- path_input_frame = tk.LabelFrame(self.tab_path, text="📁 Select Execution Directory", bg="#2d2d2d", fg="white")
- path_input_frame.pack(fill="x", padx=10, pady=10)
- tk.Label(path_input_frame, text="Directory Path:", bg="#2d2d2d", fg="#00ff00").grid(row=0, column=0, padx=5, pady=5, sticky="w")
- self.path_executor_entry = tk.Entry(path_input_frame, width=70, bg="#333", fg="white", insertbackground="white", font=("Consolas", 10))
- self.path_executor_entry.grid(row=0, column=1, padx=5, pady=5)
- self.path_executor_entry.insert(0, os.getcwd())
- tk.Button(path_input_frame, text="🗂️ Browse", command=self.browse_executor_path,
- bg="#007acc", fg="white", relief="flat", padx=15, cursor="hand2").grid(row=0, column=2, padx=5, pady=5)
- tk.Button(path_input_frame, text="✓ Validate", command=self.validate_executor_path,
- bg="#28a745", fg="white", relief="flat", padx=10, cursor="hand2").grid(row=0, column=3, padx=5, pady=5)
- # Quick Paths Grid
- quick_frame = tk.LabelFrame(self.tab_path, text="⚡ Quick Access Paths", bg="#2d2d2d", fg="white")
- quick_frame.pack(fill="x", padx=10, pady=10)
- row, col = 0, 0
- for name, path in QUICK_PATHS.items():
- tk.Button(quick_frame, text=f"📁 {name}", command=lambda p=path: self.set_executor_path(p),
- bg="#3a3a3a", fg="cyan", relief="flat", padx=10, pady=3, cursor="hand2").grid(row=row, column=col, padx=3, pady=3)
- col += 1
- if col > 3:
- col = 0
- row += 1
- # Command Input Section
- cmd_frame = tk.LabelFrame(self.tab_path, text="▶ Enter Command to Execute", bg="#2d2d2d", fg="white")
- cmd_frame.pack(fill="both", expand=True, padx=10, pady=10)
- tk.Label(cmd_frame, text="Command:", bg="#2d2d2d", fg="#00ff00").pack(anchor="w", padx=5, pady=2)
- self.executor_cmd = tk.Text(cmd_frame, height=4, bg="#1e1e1e", fg="white", font=("Consolas", 10), insertbackground="white")
- self.executor_cmd.pack(fill="x", padx=5, pady=5)
- exec_ctrl = tk.Frame(cmd_frame, bg="#2d2d2d")
- exec_ctrl.pack(fill="x", padx=5, pady=5)
- tk.Button(exec_ctrl, text="▶ Run in Selected Dir", command=self.run_executor_command,
- bg="#007acc", fg="white", relief="flat", padx=20, pady=5, cursor="hand2").pack(side="left", padx=5)
- tk.Button(exec_ctrl, text="⚡ Run as Admin", command=lambda: self.run_executor_command(admin=True),
- bg="#dc3545", fg="white", relief="flat", padx=20, pady=5, cursor="hand2").pack(side="left", padx=5)
- tk.Button(exec_ctrl, text="📋 Copy Command", command=self.copy_executor_command,
- bg="#555", fg="white", relief="flat", padx=15, pady=5, cursor="hand2").pack(side="left", padx=5)
- tk.Button(exec_ctrl, text="🗑️ Clear", command=lambda: self.executor_cmd.delete(1.0, tk.END),
- bg="#555", fg="white", relief="flat", padx=15, pady=5, cursor="hand2").pack(side="right", padx=5)
- tk.Label(cmd_frame, text="📊 Current Directory:", bg="#2d2d2d", fg="yellow").pack(anchor="w", padx=5, pady=2)
- self.executor_path_lbl = tk.Label(cmd_frame, text=os.getcwd(), bg="#1e1e1e", fg="lime", font=("Consolas", 9), anchor="w")
- self.executor_path_lbl.pack(fill="x", padx=5, pady=2)
- list_frame = tk.Frame(cmd_frame, bg="#2d2d2d")
- list_frame.pack(fill="both", expand=True, padx=5, pady=10)
- tk.Label(list_frame, text="📄 Files in Directory:", bg="#2d2d2d", fg="cyan").pack(anchor="w")
- self.file_listbox = tk.Listbox(list_frame, bg="#1e1e1e", fg="white", font=("Consolas", 9))
- self.file_listbox.pack(fill="both", expand=True, pady=5)
- tk.Button(list_frame, text="🔄 Refresh File List", command=self.refresh_file_list,
- bg="#555", fg="white", relief="flat", cursor="hand2").pack(pady=5)
- def setup_system_tab(self):
- """Setup System & Network tab"""
- info_frame = tk.LabelFrame(self.tab_sys, text="System Information", bg="#2d2d2d", fg="white")
- info_frame.pack(fill="x", padx=10, pady=10)
- self.sys_info_text = tk.Text(info_frame, height=8, bg="#1e1e1e", fg="cyan")
- self.sys_info_text.pack(fill="x", padx=5, pady=5)
- self.refresh_sys_info()
- net_frame = tk.LabelFrame(self.tab_sys, text="Network Tools", bg="#2d2d2d", fg="white")
- net_frame.pack(fill="both", expand=True, padx=10, pady=10)
- tk.Button(net_frame, text="📡 Get IP Config", command=self.get_ip_config, cursor="hand2").pack(side="left", padx=10, pady=10)
- tk.Button(net_frame, text="📶 Ping Google", command=self.ping_google, cursor="hand2").pack(side="left", padx=10, pady=10)
- tk.Button(net_frame, text="🌐 Flush DNS", command=self.flush_dns, cursor="hand2").pack(side="left", padx=10, pady=10)
- tk.Button(net_frame, text="📋 Copy Output", command=self.copy_last_output, cursor="hand2").pack(side="left", padx=10, pady=10)
- self.cpu_lbl = tk.Label(self.tab_sys, text="CPU: 0%", fg="lime", bg="#1e1e1e", font=("Arial", 12, "bold"))
- self.cpu_lbl.pack(side="left", padx=20)
- self.ram_lbl = tk.Label(self.tab_sys, text="RAM: 0%", fg="yellow", bg="#1e1e1e", font=("Arial", 12, "bold"))
- self.ram_lbl.pack(side="left", padx=20)
- def setup_process_tab(self):
- """Setup Process Manager tab"""
- tk.Label(self.tab_proc, text="Running Processes (Top 50)", bg="#2d2d2d", fg="white").pack(pady=5)
- self.proc_list = ttk.Treeview(self.tab_proc, columns=("Name", "PID", "CPU"), show="headings")
- self.proc_list.heading("Name", text="Process Name")
- self.proc_list.heading("PID", text="PID")
- self.proc_list.heading("CPU", text="CPU %")
- self.proc_list.pack(fill="both", expand=True, padx=10, pady=5)
- tk.Button(self.tab_proc, text="🔄 Refresh List", command=self.refresh_processes, cursor="hand2").pack(pady=5)
- tk.Button(self.tab_proc, text="💀 Kill Selected", command=self.kill_process, bg="#cc3333", fg="white", cursor="hand2").pack(pady=5)
- def create_menu(self):
- """Create main menu bar"""
- menubar = tk.Menu(self.root)
- self.root.config(menu=menubar)
- file_menu = tk.Menu(menubar, tearoff=0)
- menubar.add_cascade(label="File", menu=file_menu)
- file_menu.add_command(label="Export Commands", command=self.export_commands)
- file_menu.add_command(label="Import Commands", command=self.import_commands)
- file_menu.add_separator()
- file_menu.add_command(label="Exit", command=self.on_close)
- edit_menu = tk.Menu(menubar, tearoff=0)
- menubar.add_cascade(label="Edit", menu=edit_menu)
- edit_menu.add_command(label="Edit Selected Command", command=self.edit_selected_command)
- edit_menu.add_command(label="Copy Selected Command", command=self.copy_selected_command)
- path_menu = tk.Menu(menubar, tearoff=0)
- menubar.add_cascade(label="Path", menu=path_menu)
- path_menu.add_command(label="Set Working Directory", command=self.browse_path)
- path_menu.add_command(label="Reset to Default", command=self.reset_path)
- path_menu.add_separator()
- for name, path in QUICK_PATHS.items():
- path_menu.add_command(label=f"📁 {name}", command=lambda p=path: self.set_path(p))
- help_menu = tk.Menu(menubar, tearoff=0)
- menubar.add_cascade(label="Help", menu=help_menu)
- help_menu.add_command(label="About", command=self.show_about)
- help_menu.add_command(label="Keyboard Shortcuts", command=self.show_shortcuts)
- # ==================== PATH MANAGEMENT ====================
- def browse_path(self):
- """Browse and select folder for command execution"""
- path = filedialog.askdirectory(title="Select Working Directory", initialdir=self.work_dir.get())
- if path:
- self.work_dir.set(path)
- self.validate_path()
- self.log(f"[PATH] Working directory: {path}\n")
- self.update_status()
- def browse_executor_path(self):
- """Browse path for Path Executor tab"""
- path = filedialog.askdirectory(title="Select Execution Directory", initialdir=self.path_executor_entry.get())
- if path:
- self.path_executor_entry.delete(0, tk.END)
- self.path_executor_entry.insert(0, path)
- self.executor_path_lbl.config(text=path)
- self.validate_executor_path()
- self.refresh_file_list()
- def validate_path(self):
- """Validate working directory path"""
- path = self.work_dir.get().strip()
- if validate_directory(path):
- self.path_status.config(text="✓ Valid", fg="lime")
- self.config["work_dir"] = path
- self.save_config()
- return True
- else:
- self.path_status.config(text="✗ Invalid", fg="red")
- messagebox.showwarning("Invalid Path", f"Directory does not exist:\n{path}")
- return False
- def validate_executor_path(self):
- """Validate path in Path Executor tab"""
- path = self.path_executor_entry.get().strip()
- if validate_directory(path):
- self.executor_path_lbl.config(text=path, fg="lime")
- self.refresh_file_list()
- self.log(f"[PATH-EXEC] Validated: {path}\n")
- return True
- else:
- self.executor_path_lbl.config(text=path, fg="red")
- messagebox.showwarning("Invalid Path", f"Directory does not exist:\n{path}")
- return False
- def set_quick_path(self, selection):
- """Set path from quick access dropdown"""
- if selection and selection != "Quick Paths ▼" and selection in QUICK_PATHS:
- path = QUICK_PATHS[selection]
- self.work_dir.set(path)
- self.validate_path()
- self.log(f"[PATH] Quick path: {selection} → {path}\n")
- self.path_var.set("Quick Paths ▼")
- self.update_status()
- def set_path(self, path):
- """Set working directory programmatically"""
- self.work_dir.set(path)
- self.validate_path()
- self.update_status()
- def set_executor_path(self, path):
- """Set path in Path Executor tab"""
- self.path_executor_entry.delete(0, tk.END)
- self.path_executor_entry.insert(0, path)
- self.executor_path_lbl.config(text=path)
- self.validate_executor_path()
- def reset_path(self):
- """Reset working directory to default"""
- default = os.getcwd()
- self.work_dir.set(default)
- self.validate_path()
- self.log(f"[PATH] Reset to: {default}\n")
- self.update_status()
- def update_status(self):
- """Update status bar with current path"""
- path = self.work_dir.get()
- display = path if len(path) <= 50 else path[:47] + "..."
- self.status_var.set(f"Ready | Work Dir: {display}")
- def refresh_file_list(self):
- """List files in selected executor directory"""
- self.file_listbox.delete(0, tk.END)
- path = self.path_executor_entry.get().strip()
- if not validate_directory(path):
- self.file_listbox.insert(tk.END, "⚠️ Invalid directory")
- return
- try:
- items = os.listdir(path)
- for item in sorted(items):
- full_path = os.path.join(path, item)
- prefix = "📁 " if os.path.isdir(full_path) else "📄 "
- self.file_listbox.insert(tk.END, f"{prefix}{item}")
- except PermissionError:
- self.file_listbox.insert(tk.END, "⚠️ Access Denied")
- except Exception as e:
- self.file_listbox.insert(tk.END, f"Error: {e}")
- # ==================== PATH EXECUTOR ====================
- def run_executor_command(self, admin=False):
- """Execute command from Path Executor tab"""
- cmd = self.executor_cmd.get(1.0, tk.END).strip()
- path = self.path_executor_entry.get().strip()
- if not cmd:
- messagebox.showinfo("Info", "Please enter a command to execute.")
- return
- if not validate_directory(path):
- if not messagebox.askyesno("Invalid Path", f"Directory does not exist:\n{path}\n\nRun anyway with default directory?"):
- return
- path = None
- self.log(f"[EXEC-PATH] Directory: {path or 'DEFAULT'}\n")
- self.log(f"[EXEC-CMD] {cmd}\n")
- if admin:
- full_cmd = f'cd /d "{path}" && {cmd} && pause' if path else f'{cmd} && pause'
- ctypes.windll.shell32.ShellExecuteW(None, "runas", "cmd.exe", f"/c {full_cmd}", None, 1)
- self.log(f"[ADMIN] Launched in new window\n")
- else:
- self.run_thread(cmd, work_dir=path)
- def copy_executor_command(self):
- """Copy command from Path Executor to clipboard"""
- cmd = self.executor_cmd.get(1.0, tk.END).strip()
- if cmd:
- if safe_clipboard_copy(cmd, self.root):
- messagebox.showinfo("Copied", f"Command copied:\n{cmd}")
- else:
- messagebox.showerror("Error", "Failed to copy to clipboard")
- # ==================== CONTEXT MENU & CLIPBOARD ====================
- def show_context_menu(self, event):
- """Show right-click context menu"""
- index = self.cmd_listbox.nearest(event.y)
- self.cmd_listbox.selection_clear(0, tk.END)
- self.cmd_listbox.selection_set(index)
- self.cmd_listbox.activate(index)
- try:
- self.context_menu.tk_popup(event.x_root, event.y_root)
- finally:
- self.context_menu.grab_release()
- def edit_selected_command(self):
- """Edit command in database"""
- cmds = self.get_selected_commands_with_meta()
- if not cmds:
- messagebox.showinfo("Info", "Please select a command to edit.")
- return
- cat, original_cmd = cmds[0]
- edited_cmd = simpledialog.askstring("✏️ Edit Command", f"Edit in '{cat}':", initialvalue=original_cmd, parent=self.root)
- if edited_cmd and edited_cmd.strip():
- edited_cmd = edited_cmd.strip()
- if original_cmd in self.favorites and edited_cmd != original_cmd:
- self.favorites.remove(original_cmd)
- self.favorites.add(edited_cmd)
- self.save_favorites()
- if cat in self.commands and original_cmd in self.commands[cat]:
- idx = self.commands[cat].index(original_cmd)
- self.commands[cat][idx] = edited_cmd
- self.save_commands()
- self.on_category_select()
- self.log(f"[EDITED] '{original_cmd}' → '{edited_cmd}'\n")
- messagebox.showinfo("Success", "Command updated!")
- def copy_selected_command(self):
- """Copy selected command to clipboard"""
- cmds = self.get_selected_commands()
- if not cmds:
- messagebox.showinfo("Info", "Please select a command to copy.")
- return
- cmd_text = cmds[0]
- if safe_clipboard_copy(cmd_text, self.root):
- self.log(f"[COPIED] '{cmd_text}'\n")
- self.status_var.set(f"Copied: {cmd_text[:50]}...")
- messagebox.showinfo("Copied!", cmd_text)
- else:
- messagebox.showerror("Error", "Failed to copy")
- def copy_console(self):
- """Copy entire console to clipboard"""
- if self.console is None: return
- content = self.console.get(1.0, tk.END)
- if safe_clipboard_copy(content, self.root):
- messagebox.showinfo("Copied", "Console log copied!")
- else:
- messagebox.showerror("Error", "Failed to copy")
- def copy_last_output(self):
- """Copy last output to clipboard"""
- content = self.console.get(1.0, tk.END) if self.console else ""
- if safe_clipboard_copy(content, self.root):
- self.log("[COPIED] Output to clipboard\n")
- def edit_and_run(self):
- """Edit command before running"""
- cmds = self.get_selected_commands_with_meta()
- if not cmds:
- messagebox.showinfo("Info", "Please select a command.")
- return
- cat, original_cmd = cmds[0]
- run_cmd = simpledialog.askstring("▶ Edit & Run", "Modify command:", initialvalue=original_cmd, parent=self.root)
- if run_cmd is not None:
- cmd_to_run = run_cmd.strip() if run_cmd.strip() else original_cmd
- self.run_thread(cmd_to_run)
- # ==================== SELECTION HELPERS ====================
- def get_selected_commands_with_meta(self):
- """Return (category, command) tuples for selected items"""
- if self.cmd_listbox is None: return []
- try:
- indices = self.cmd_listbox.curselection()
- if not indices:
- active = self.cmd_listbox.index(tk.ACTIVE)
- if active >= 0: indices = [active]
- else: return []
- results = []
- current_cat = None
- if self.cat_listbox and self.cat_listbox.curselection():
- cat_idx = self.cat_listbox.curselection()[0]
- current_cat = self.cat_listbox.get(cat_idx)
- for i in indices:
- val = self.cmd_listbox.get(i).strip()
- if val.startswith("⭐ "): val = val[3:]
- if current_cat:
- results.append((current_cat, val))
- else:
- for cat, cmds in self.commands.items():
- if val in cmds:
- results.append((cat, val))
- break
- return results
- except:
- return []
- def get_selected_commands(self):
- """Return command strings for selected items"""
- if self.cmd_listbox is None: return []
- try:
- indices = self.cmd_listbox.curselection()
- if not indices:
- active = self.cmd_listbox.index(tk.ACTIVE)
- if active >= 0: indices = [active]
- else: return []
- cmds = []
- for i in indices:
- val = self.cmd_listbox.get(i).strip()
- if val.startswith("⭐ "): val = val[3:]
- cmds.append(val)
- return cmds
- except:
- return []
- # ==================== SEARCH FUNCTION (✅ DEFINED BEFORE USE) ====================
- def search_command(self):
- """Filter commands based on search query - ✅ NOW PROPERLY DEFINED"""
- if self.cmd_listbox is None:
- return
- query = self.search_var.get().lower()
- self.cmd_listbox.delete(0, tk.END)
- if not query:
- self.on_category_select()
- return
- for cat, cmds in self.commands.items():
- for cmd in cmds:
- if query in cmd.lower():
- prefix = "⭐ " if cmd in self.favorites else " "
- self.cmd_listbox.insert(tk.END, f"{prefix}{cmd}")
- # ==================== COMMAND EXECUTION ====================
- def check_safety(self, cmd):
- """Check for dangerous keywords"""
- for key in DANGEROUS_KEYWORDS:
- if key in cmd.lower():
- return messagebox.askyesno("⚠️ DANGER", f"Command contains '{key}'.\nRun anyway?", icon="warning")
- return True
- def run_thread(self, cmd, is_admin=False, work_dir=None):
- """Run command in background thread"""
- def task():
- try:
- if not self.check_safety(cmd):
- self.log_queue.put(f"[BLOCKED] Cancelled: {cmd}\n")
- return
- exec_dir = work_dir if work_dir and validate_directory(work_dir) else self.work_dir.get()
- if not validate_directory(exec_dir):
- exec_dir = os.getcwd()
- timestamp = time.strftime("%H:%M:%S")
- self.log_queue.put(f"\n[{timestamp}] Dir: {exec_dir}\n[CMD] {cmd}\n{'='*60}\n")
- if is_admin:
- full_cmd = f'cd /d "{exec_dir}" && {cmd} && pause'
- ctypes.windll.shell32.ShellExecuteW(None, "runas", "cmd.exe", f"/c {full_cmd}", None, 1)
- self.log_queue.put(f"[ADMIN] Launched\n")
- else:
- process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
- text=True, encoding='oem', errors='ignore', cwd=exec_dir)
- for line in process.stdout:
- self.log_queue.put(line)
- process.wait()
- self.log_queue.put(f"\n[FINISHED] Exit: {process.returncode}\n")
- except Exception as e:
- self.log_queue.put(f"[ERROR] {e}\n")
- threading.Thread(target=task, daemon=True).start()
- def run_selected(self):
- """Run selected command(s)"""
- cmds = self.get_selected_commands()
- if not cmds:
- messagebox.showinfo("Info", "Select a command to run.")
- return
- for cmd in cmds:
- self.run_thread(cmd)
- def run_admin_selected(self):
- """Run selected command as admin"""
- cmds = self.get_selected_commands()
- if not cmds:
- messagebox.showinfo("Info", "Select a command.")
- return
- for cmd in cmds:
- self.run_thread(cmd, is_admin=True)
- def run_batch(self):
- """Run multiple commands"""
- script = simpledialog.askstring("Batch Runner", "Commands (one per line):", parent=self.root)
- if script:
- for line in script.splitlines():
- if line.strip():
- self.run_thread(line.strip())
- def multi_select(self, event):
- """Handle Ctrl+Click multi-select"""
- pass
- def toggle_fav(self):
- """Toggle favorite status"""
- cmds = self.get_selected_commands()
- if not cmds: return
- cmd = cmds[0]
- if cmd in self.favorites:
- self.favorites.remove(cmd)
- else:
- self.favorites.add(cmd)
- self.save_favorites()
- self.on_category_select()
- def add_command(self):
- """Add new command"""
- cmd = simpledialog.askstring("Add Command", "Enter Command:", parent=self.root)
- if cmd and cmd.strip():
- cmd = cmd.strip()
- cat = simpledialog.askstring("Category", "Enter Category:", parent=self.root) or "Custom"
- if cat not in self.commands:
- self.commands[cat] = []
- if self.cat_listbox: self.cat_listbox.insert(tk.END, cat)
- self.commands[cat].append(cmd)
- self.save_commands()
- self.on_category_select()
- def delete_command(self):
- """Delete selected command"""
- cmds = self.get_selected_commands()
- if not cmds: return
- cmd = cmds[0]
- if messagebox.askyesno("Delete?", f"Delete:\n{cmd}"):
- for c in self.commands:
- if cmd in self.commands[c]:
- self.commands[c].remove(cmd)
- if cmd in self.favorites:
- self.favorites.remove(cmd)
- self.save_commands()
- self.save_favorites()
- self.on_category_select()
- # ==================== DATA LOADING/SAVING ====================
- def load_commands(self):
- """Load commands from database file"""
- self.commands.clear()
- if self.cat_listbox: self.cat_listbox.delete(0, tk.END)
- default_cats = [] #["System", "Network", "Files", "Custom"]
- if os.path.exists(FILE_NAME):
- try:
- with open(FILE_NAME, "r", encoding="utf-8") as f:
- current_cat = "General"
- for line in f:
- line = line.strip()
- if line.startswith("[") and line.endswith("]"):
- current_cat = line[1:-1]
- if current_cat not in self.commands:
- self.commands[current_cat] = []
- elif line:
- if current_cat not in self.commands:
- self.commands[current_cat] = []
- self.commands[current_cat].append(line)
- except Exception as e:
- self.log(f"Error loading DB: {e}\n")
- self.commands = {c: [] for c in default_cats}
- else:
- self.commands = {c: [] for c in default_cats}
- self.save_commands()
- if self.cat_listbox:
- for cat in sorted(self.commands.keys()):
- self.cat_listbox.insert(tk.END, cat)
- if self.cat_listbox.size() > 0:
- self.cat_listbox.selection_set(0)
- self.on_category_select()
- def save_commands(self):
- """Save commands to database file"""
- try:
- with open(FILE_NAME, "w", encoding="utf-8") as f:
- for cat, cmds in self.commands.items():
- f.write(f"[{cat}]\n")
- for cmd in cmds:
- f.write(f"{cmd}\n")
- except Exception as e:
- messagebox.showerror("Save Error", str(e))
- def on_category_select(self, event=None):
- """Update command list when category changes"""
- try:
- if not self.cat_listbox or not self.cmd_listbox: return
- idx = self.cat_listbox.curselection()[0]
- cat = self.cat_listbox.get(idx)
- self.cmd_listbox.delete(0, tk.END)
- for cmd in self.commands.get(cat, []):
- prefix = "⭐ " if cmd in self.favorites else " "
- self.cmd_listbox.insert(tk.END, f"{prefix}{cmd}")
- except IndexError:
- pass
- def load_favorites(self):
- """Load favorites from JSON"""
- if os.path.exists(FAV_FILE):
- try:
- with open(FAV_FILE, "r") as f:
- self.favorites = set(json.load(f))
- except:
- self.favorites = set()
- def save_favorites(self):
- """Save favorites to JSON"""
- try:
- with open(FAV_FILE, "w") as f:
- json.dump(list(self.favorites), f)
- except:
- pass
- def load_config(self):
- """Load config from JSON"""
- if os.path.exists(CONFIG_FILE):
- try:
- with open(CONFIG_FILE, "r") as f:
- self.config = json.load(f)
- if "geometry" in self.config:
- self.root.geometry(self.config["geometry"])
- if "work_dir" in self.config and validate_directory(self.config["work_dir"]):
- self.work_dir.set(self.config["work_dir"])
- except:
- pass
- def save_config(self):
- """Save config to JSON"""
- self.config["geometry"] = self.root.geometry()
- self.config["work_dir"] = self.work_dir.get()
- try:
- with open(CONFIG_FILE, "w") as f:
- json.dump(self.config, f)
- except:
- pass
- def export_commands(self):
- """Export commands to JSON"""
- file = filedialog.asksaveasfilename(defaultextension=".json", filetypes=[("JSON", "*.json")])
- if file:
- try:
- with open(file, "w", encoding="utf-8") as f:
- json.dump(self.commands, f, indent=4)
- messagebox.showinfo("Success", "Exported!")
- except Exception as e:
- messagebox.showerror("Error", str(e))
- def import_commands(self):
- """Import commands from JSON"""
- file = filedialog.askopenfilename(filetypes=[("JSON", "*.json")])
- if file:
- try:
- with open(file, "r", encoding="utf-8") as f:
- data = json.load(f)
- count = 0
- for cat, cmds in data.items():
- if cat not in self.commands: self.commands[cat] = []
- for cmd in cmds:
- if cmd not in self.commands[cat]:
- self.commands[cat].append(cmd)
- count += 1
- self.save_commands()
- self.load_commands()
- messagebox.showinfo("Success", f"Imported {count} commands!")
- except Exception as e:
- messagebox.showerror("Error", str(e))
- # ==================== SYSTEM MONITORING ====================
- def refresh_sys_info(self):
- """Refresh system information display"""
- try:
- import psutil
- info = f"OS: {os.name} | Python: {sys.version.split()[0]}\n"
- info += f"Cores: {psutil.cpu_count(logical=False)} | Threads: {psutil.cpu_count(logical=True)}\n"
- info += f"Boot: {time.ctime(psutil.boot_time())}"
- self.sys_info_text.delete(1.0, tk.END)
- self.sys_info_text.insert(tk.END, info)
- except ImportError:
- self.sys_info_text.insert(tk.END, "Install psutil: pip install psutil")
- except Exception as e:
- self.sys_info_text.insert(tk.END, f"Error: {e}")
- def update_monitor(self):
- """Update CPU/RAM monitors"""
- try:
- import psutil
- cpu = psutil.cpu_percent(interval=0.5)
- ram = psutil.virtual_memory().percent
- self.cpu_lbl.config(text=f"CPU: {cpu}%", fg="red" if cpu > 80 else "orange" if cpu > 50 else "lime")
- self.ram_lbl.config(text=f"RAM: {ram}%", fg="red" if ram > 80 else "orange" if ram > 50 else "yellow")
- except:
- pass
- self.root.after(2000, self.update_monitor)
- def refresh_processes(self):
- """Refresh process list"""
- for item in self.proc_list.get_children():
- self.proc_list.delete(item)
- try:
- import psutil
- procs = []
- for p in psutil.process_iter(['pid', 'name', 'cpu_percent']):
- try:
- info = p.info
- if info['cpu_percent'] is None: info['cpu_percent'] = 0.0
- procs.append(info)
- except: pass
- procs.sort(key=lambda x: x['cpu_percent'] or 0, reverse=True)
- for p in procs[:50]:
- self.proc_list.insert("", "end", values=(p['name'] or "Unknown", p['pid'], f"{p['cpu_percent'] or 0:.1f}%"))
- except ImportError:
- messagebox.showinfo("Info", "Install psutil: pip install psutil")
- except Exception as e:
- messagebox.showerror("Error", str(e))
- def kill_process(self):
- """Kill selected process"""
- selected = self.proc_list.selection()
- if not selected: return
- item = self.proc_list.item(selected[0])
- pid = item['values'][1]
- if messagebox.askyesno("Kill?", f"Kill PID {pid}?"):
- try:
- subprocess.call(f"taskkill /PID {pid} /F", shell=True)
- self.refresh_processes()
- except Exception as e:
- messagebox.showerror("Error", str(e))
- def get_ip_config(self): self.run_thread("ipconfig /all")
- def ping_google(self): self.run_thread("ping google.com -n 4")
- def flush_dns(self): self.run_thread("ipconfig /flushdns")
- # ==================== UTILITIES ====================
- def log(self, message):
- """Add message to log queue"""
- self.log_queue.put(message)
- def process_log_queue(self):
- """Process log queue and update console"""
- try:
- while True:
- msg = self.log_queue.get_nowait()
- if self.console:
- self.console.insert(tk.END, msg)
- self.console.see(tk.END)
- except queue.Empty:
- pass
- self.root.after(100, self.process_log_queue)
- def save_log(self):
- """Save console log to file"""
- if not self.console: return
- file = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text", "*.txt")])
- if file:
- try:
- with open(file, "w", encoding="utf-8") as f:
- f.write(self.console.get(1.0, tk.END))
- except Exception as e:
- messagebox.showerror("Error", str(e))
- def show_about(self):
- """Show about dialog"""
- messagebox.showinfo("About", f"NAJEEB CLI PRO MAX V{VERSION}\nWin7-32Bit | Python 3.7.9\n\nUse responsibly! ⚠️")
- def show_shortcuts(self):
- """Show keyboard shortcuts"""
- messagebox.showinfo("Shortcuts", "Ctrl+E: Edit | Ctrl+C: Copy | Ctrl+B: Browse Path | Enter: Run")
- def on_close(self):
- """Handle window close"""
- self.save_config()
- if messagebox.askyesno("Exit", "Save and exit?"):
- self.root.destroy()
- # ==================== KEYBOARD SHORTCUTS ====================
- def bind_shortcuts(app):
- app.root.bind("<Control-e>", lambda e: app.edit_selected_command())
- app.root.bind("<Control-c>", lambda e: app.copy_selected_command())
- app.root.bind("<Control-b>", lambda e: app.browse_path())
- app.root.bind("<Control-f>", lambda e: app.search_var.entrywidget.focus_set() if app.search_var else None)
- app.root.bind("<Return>", lambda e: app.run_selected())
- # ==================== MAIN ENTRY POINT ====================
- if __name__ == "__main__":
- # High DPI Fix
- try:
- ctypes.windll.shcore.SetProcessDpiAwareness(1)
- except:
- pass
- root = tk.Tk()
- try:
- root.iconbitmap(default='')
- except:
- pass
- app = GodModeV7(root)
- bind_shortcuts(app)
- app.log("✅ Ready | Right-click commands for options\n")
- app.log("💡 Use Path Executor tab for custom directories\n\n")
- root.mainloop()
Add Comment
Please, Sign In to add comment