Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import subprocess
- import tkinter as tk
- from tkinter import filedialog, messagebox, Listbox, Scrollbar, Entry
- import ctypes
- import sys
- import string
- def is_admin():
- """ Check if the script is running with admin privileges """
- try:
- return ctypes.windll.shell32.IsUserAnAdmin()
- except:
- return False
- def browse_vhd():
- """ Browse for a VHD file and display its path in the entry field """
- vhd_file = filedialog.askopenfilename(filetypes=[("VHD files", "*.vhd")])
- if vhd_file:
- vhd_entry.delete(0, tk.END) # Clear existing entry
- vhd_entry.insert(0, vhd_file) # Insert selected file path
- def get_drive_letters():
- """ Get a list of current drive letters """
- return [d for d in string.ascii_uppercase if os.path.exists(f"{d}:\\")]
- def mount_vhd():
- """ Mount the selected VHD file using DiskPart and auto-detect the new drive """
- vhd_file = vhd_entry.get()
- # Ensure a VHD file is selected
- if not vhd_file.endswith('.vhd'):
- messagebox.showerror("Invalid File", "Please select a valid .vhd file.")
- return
- # Ensure the file exists
- if not os.path.exists(vhd_file):
- messagebox.showerror("File Not Found", "The selected VHD file does not exist.")
- return
- # Correct the path format (convert / to \)
- vhd_file = vhd_file.replace("/", "\\")
- # Get current drive letters before mounting
- drives_before = get_drive_letters()
- try:
- # Create a DiskPart script to mount the VHD
- diskpart_script = f"""
- select vdisk file="{vhd_file}"
- attach vdisk
- """
- script_path = 'mount_vhd.txt'
- # Write the DiskPart script to a file
- with open(script_path, 'w') as f:
- f.write(diskpart_script.strip())
- # Execute the DiskPart command with the script
- result = subprocess.run(['diskpart', '/s', script_path], capture_output=True, text=True)
- # Check if DiskPart ran successfully
- if result.returncode == 0:
- messagebox.showinfo("Success", f"VHD file {vhd_file} mounted successfully.")
- # Get the new drive letters after mounting
- drives_after = get_drive_letters()
- new_drive = list(set(drives_after) - set(drives_before)) # Find the new drive letter
- if new_drive:
- mounted_drive = new_drive[0] + ":\\"
- print(f"VHD mounted at {mounted_drive}")
- show_files_in_vhd(mounted_drive) # Show files in the new drive
- else:
- messagebox.showerror("Error", "No new drive detected. Mounting might have failed.")
- else:
- # Capture and show detailed DiskPart error output
- error_message = f"DiskPart failed with error:\n{result.stderr}"
- print(error_message) # Print error to console
- messagebox.showerror("DiskPart Error", error_message)
- except Exception as e:
- messagebox.showerror("Error", f"An error occurred: {e}")
- finally:
- # Clean up the DiskPart script file
- if os.path.exists(script_path):
- os.remove(script_path)
- def unmount_vhd():
- """ Unmount the selected VHD file using DiskPart """
- vhd_file = vhd_entry.get()
- # Ensure a VHD file is selected
- if not vhd_file.endswith('.vhd'):
- messagebox.showerror("Invalid File", "Please select a valid .vhd file.")
- return
- # Ensure the file exists
- if not os.path.exists(vhd_file):
- messagebox.showerror("File Not Found", "The selected VHD file does not exist.")
- return
- # Correct the path format (convert / to \)
- vhd_file = vhd_file.replace("/", "\\")
- try:
- # Create a DiskPart script to unmount the VHD
- diskpart_script = f"""
- select vdisk file="{vhd_file}"
- detach vdisk
- """
- script_path = 'unmount_vhd.txt'
- # Write the DiskPart script to a file
- with open(script_path, 'w') as f:
- f.write(diskpart_script.strip())
- # Execute the DiskPart command with the script
- result = subprocess.run(['diskpart', '/s', script_path], capture_output=True, text=True)
- # Check if DiskPart ran successfully
- if result.returncode == 0:
- messagebox.showinfo("Success", f"VHD file {vhd_file} unmounted successfully.")
- # Clear file list after unmounting
- file_list.delete(0, tk.END)
- else:
- # Capture and show detailed DiskPart error output
- error_message = f"DiskPart failed with error:\n{result.stderr}"
- print(error_message) # Print error to console
- messagebox.showerror("DiskPart Error", error_message)
- except Exception as e:
- messagebox.showerror("Error", f"An error occurred: {e}")
- finally:
- # Clean up the DiskPart script file
- if os.path.exists(script_path):
- os.remove(script_path)
- def show_files_in_vhd(mounted_drive):
- """ Show all files and folders inside the mounted VHD """
- if not os.path.exists(mounted_drive):
- messagebox.showerror("Error", "The mounted drive does not exist.")
- return
- # Clear the file list before adding new items
- file_list.delete(0, tk.END)
- global all_files # Use the global all_files variable
- all_files = [] # Reset the all_files list
- for root, dirs, files in os.walk(mounted_drive):
- for name in dirs:
- full_path = os.path.join(root, name)
- file_list.insert(tk.END, full_path)
- all_files.append(full_path) # Add directory to all_files
- for name in files:
- full_path = os.path.join(root, name)
- file_list.insert(tk.END, full_path)
- all_files.append(full_path) # Add file to all_files
- def open_file(event):
- """ Open the selected file with the default program """
- selected_file = file_list.get(file_list.curselection())
- os.startfile(selected_file) # Open with default program
- def search_files():
- """ Search for files in the mounted VHD """
- search_query = search_entry.get().lower()
- if not all_files: # Check if all_files is populated
- messagebox.showerror("Error", "No files to search. Make sure the VHD is mounted.")
- return
- file_list.delete(0, tk.END) # Clear the file list
- for item in all_files: # Use the global all_files variable
- if search_query in os.path.basename(item).lower():
- file_list.insert(tk.END, item)
- def main():
- """ Main function to run the application """
- if is_admin():
- global all_files # Store all files in a global variable
- all_files = [] # Initialize all_files
- # Tkinter GUI setup
- root = tk.Tk()
- root.title("Najeeb VHD Mounter")
- # Set the window size to 900x600
- root.geometry("1000x700")
- # VHD selection
- vhd_label = tk.Label(root, text="Select VHD File:", font=("Arial", 14), bg="lightblue")
- vhd_label.grid(row=0, column=0, padx=10, pady=10, sticky='w')
- global vhd_entry
- vhd_entry = tk.Entry(root, width=60, font=("Arial", 14))
- vhd_entry.grid(row=0, column=1, padx=10, pady=10)
- browse_button = tk.Button(root, text="Browse", command=browse_vhd, font=("Arial", 12), bg="lightgreen")
- browse_button.grid(row=0, column=2, padx=10, pady=10)
- # Mount button
- mount_button = tk.Button(root, text="Mount VHD", command=mount_vhd, font=("Arial", 12), bg="lightgreen")
- mount_button.grid(row=1, column=0, padx=10, pady=10)
- # Unmount button
- unmount_button = tk.Button(root, text="Unmount VHD", command=unmount_vhd, font=("Arial", 12), bg="lightgreen")
- unmount_button.grid(row=1, column=2, padx=10, pady=10)
- # File Listbox with scrollbar
- global file_list
- file_list = Listbox(root, width=106, height=25, font=("Arial", 12))
- file_list.grid(row=2, column=0, columnspan=3, padx=10, pady=10)
- scrollbar = Scrollbar(root)
- scrollbar.grid(row=2, column=3, sticky='ns')
- file_list.config(yscrollcommand=scrollbar.set)
- scrollbar.config(command=file_list.yview)
- # Bind double-click to open file
- file_list.bind('<Double-Button-1>', open_file)
- # Search functionality
- search_label = tk.Label(root, text="Search:", font=("Arial", 14), bg="lightblue")
- search_label.grid(row=3, column=0, padx=10, pady=10, sticky='w')
- global search_entry
- search_entry = Entry(root, width=60, font=("Arial", 14))
- search_entry.grid(row=3, column=1, padx=10, pady=10)
- search_button = tk.Button(root, text="Search", command=search_files, font=("Arial", 12), bg="lightgreen")
- search_button.grid(row=3, column=2, padx=10, pady=10)
- root.mainloop()
- else:
- # Rerun the script with admin privileges if not running as admin
- ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement