windows 通过Python以管理员权限运行批处理文件

ivqmmu1c  于 2023-11-21  发布在  Windows
关注(0)|答案(1)|浏览(273)

你好

我想创建一个Windows优化应用程序在Python中。我已经创建了一个复选框和运行按钮。
当“清除临时”被选中时,当我按下运行我想它运行一个批处理脚本,存储在构建文件夹。
代码如下:

  1. from tkinter import Tk, Canvas, Button, Checkbutton, PhotoImage, IntVar, Entry, Text, messagebox
  2. import os
  3. import subprocess
  4. from pathlib import Path
  5. # ? Add functionality
  6. # * Function to execute a script with admin privileges.
  7. def execute_script_as_admin(script_path):
  8. # Use the "runas" command to run the script with admin privileges.
  9. admin_command = f'runas /user:Administrator "cmd /C {script_path}"'
  10. subprocess.run(admin_command, shell=True)
  11. # * Create a functionality for
  12. # ! "Clear Temp" option
  13. # Function to get the user desktop path
  14. def get_desktop_path():
  15. return os.path.expanduser("Desktop")
  16. # Define the path to the clear_temp.bat script
  17. clear_temp_script_relative_path = "OptimizationApp\\build\\assets\\IndividualScripts\\GeneralScripts\\clear_temp.bat"
  18. # Create the full script path
  19. clear_temp_script_path = os.path.join(
  20. get_desktop_path(), clear_temp_script_relative_path)
  21. # Function to run the clear_temp.bat script
  22. def run_clear_temp_script():
  23. execute_script_as_admin(clear_temp_script_path)
  24. # * Create a functionality for
  25. # ! "Run selected" button
  26. # Function to check which checkboxes are selected and execute the corresponding scripts
  27. def run_selected_scripts():
  28. if clear_temp_var.get() == 1:
  29. run_clear_temp_script()
  30. # TODO Add more conditions for other checkboxes here
  31. # Function to be called when button_2 is clicked
  32. def on_button_2_click():
  33. if clear_temp_var.get() == 0:
  34. messagebox.showinfo("Error", "Please select at least one option!")
  35. else:
  36. run_selected_scripts()

字符串
当我运行命令,它要求管理员密码,我的电脑只有一个用户,默认情况下没有选择密码的管理员。不接受空白等
在这种情况下,我如何通过python运行批处理脚本,因为我将从上下文菜单中选择以管理员身份运行?
我试图把脚本的权利内的代码,运行的py应用程序的管理员将做的工作,我已经得到了确认消息,但没有采取任何行动。
我知道有另一种方法来清除温度,它的工作原理

  1. def clean_temp_files():
  2. username = getpass.getuser()
  3. folder_path = f"C:\\Users\\{username}\\AppData\\Local\\Temp"
  4. system_path = "C:\\Windows\\Temp"
  5. # Delete for logged user
  6. try:
  7. for item in os.listdir(folder_path):
  8. item_path = os.path.join(folder_path, item)
  9. try:
  10. if os.path.isfile(item_path):
  11. os.remove(item_path)
  12. elif os.path.isdir(item_path):
  13. shutil.rmtree(item_path)
  14. except (PermissionError, FileNotFoundError) as e:
  15. print(f"Skipped {item_path} due to error: {e}")
  16. except Exception as e:
  17. print(f"Action Failed: {e}")
  18. # Delete for System
  19. try:
  20. for item in os.listdir(system_path):
  21. item_path = os.path.join(system_path, item)
  22. try:
  23. if os.path.isfile(item_path):
  24. os.remove(item_path)
  25. elif os.path.isdir(item_path):
  26. shutil.rmtree(item_path)
  27. except (PermissionError, FileNotFoundError) as e:
  28. print(f"Skipped {item_path} due to error: {e}")
  29. except Exception as e:
  30. print(f"Action Failed: {e}")


但作为一个乞丐,它更容易为我调用预制个别脚本。和一些批处理脚本需要管理员权限运行。我使用清除临时作为例子,但我相信,一旦我找到一个solutions我可以扩大它
我看了一些类似的主题的回应,但我发现它很旧。
下面是需要的https://github.com/mcata97/windows-optimizer-app中的全部代码
最后,我想把它做成一个可执行文件,以便在需要时使用
附言:我知道互联网是充满了工具,可以做的工作,但我想尝试它做自己,看看我是否被吸引到这种“文化”,我也想使用它在另一台电脑的
感谢您的时间提前!

5us2dqdw

5us2dqdw1#

一个可能有效的修复方法是让批处理脚本使用UAC提升自己,这里是example
或者你也可以只添加一个管理员密码,如果脚本只供自己使用(我可能会有一个反正安全)
或者(可能是你想要的方式)你可以使用ctypes和runas来请求UAC提示符并以admin身份运行命令,但我不知道如何隐藏cmd窗口,如果这是一个问题:

  1. import ctypes
  2. commands = u'/k echo Hello' # replace echo Hello with your command
  3. ctypes.windll.shell32.ShellExecuteW(
  4. None,
  5. u"runas",
  6. u"cmd.exe",
  7. commands,
  8. None,
  9. 1
  10. )
  11. input() # this is here to stop the program from just exiting causing the cmd to close

字符串

展开查看全部

相关问题