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

ivqmmu1c  于 6个月前  发布在  Windows
关注(0)|答案(1)|浏览(122)

你好

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

from tkinter import Tk, Canvas, Button, Checkbutton, PhotoImage, IntVar, Entry, Text, messagebox
import os
import subprocess
from pathlib import Path

# ? Add functionality

# * Function to execute a script with admin privileges.
def execute_script_as_admin(script_path):
    # Use the "runas" command to run the script with admin privileges.
    admin_command = f'runas /user:Administrator "cmd /C {script_path}"'
    subprocess.run(admin_command, shell=True)

# * Create a functionality for
# ! "Clear Temp" option

# Function to get the user desktop path

def get_desktop_path():
    return os.path.expanduser("Desktop")

# Define the path to the clear_temp.bat script

clear_temp_script_relative_path = "OptimizationApp\\build\\assets\\IndividualScripts\\GeneralScripts\\clear_temp.bat"

# Create the full script path

clear_temp_script_path = os.path.join(
    get_desktop_path(), clear_temp_script_relative_path)

# Function to run the clear_temp.bat script

def run_clear_temp_script():
    execute_script_as_admin(clear_temp_script_path)

# * Create a functionality for
# ! "Run selected" button

# Function to check which checkboxes are selected and execute the corresponding scripts
def run_selected_scripts():
    if clear_temp_var.get() == 1:
        run_clear_temp_script()
    # TODO Add more conditions for other checkboxes here

# Function to be called when button_2 is clicked

def on_button_2_click():
    if clear_temp_var.get() == 0:
        messagebox.showinfo("Error", "Please select at least one option!")
    else:
        run_selected_scripts()

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

def clean_temp_files():
    username = getpass.getuser()
    folder_path = f"C:\\Users\\{username}\\AppData\\Local\\Temp"
    system_path = "C:\\Windows\\Temp"

    # Delete for logged user
    try:
        for item in os.listdir(folder_path):
            item_path = os.path.join(folder_path, item)
            try:
                if os.path.isfile(item_path):
                    os.remove(item_path)
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
            except (PermissionError, FileNotFoundError) as e:
                print(f"Skipped {item_path} due to error: {e}")
    except Exception as e:
        print(f"Action Failed: {e}")

    # Delete for System
    try:
        for item in os.listdir(system_path):
            item_path = os.path.join(system_path, item)
            try:
                if os.path.isfile(item_path):
                    os.remove(item_path)
                elif os.path.isdir(item_path):
                    shutil.rmtree(item_path)
            except (PermissionError, FileNotFoundError) as e:
                print(f"Skipped {item_path} due to error: {e}")
    except Exception as e:
        print(f"Action Failed: {e}")


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

5us2dqdw

5us2dqdw1#

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

import ctypes

commands = u'/k echo Hello' # replace echo Hello with your command
ctypes.windll.shell32.ShellExecuteW(
        None,
        u"runas",
        u"cmd.exe",
        commands,
        None,
        1
    )
input() # this is here to stop the program from just exiting causing the cmd to close

字符串

相关问题