You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中通过schtasks.exe向高权限PowerShell传递命令?

解决方案

核心思路

利用已创建的Powershell_Elevata高权限任务,通过临时PowerShell脚本传递需要执行的管理员命令,执行后恢复任务原有配置并清理临时文件,全程静默无窗口。

具体实现代码

import subprocess
import tempfile
import os
import time

# 定义需要执行的管理员级PowerShell命令
admin_cmd = r'New-NetFirewallRule -DisplayName "Notepad block -Outbound-" -Direction Outbound -Program "C:\Windows\System32\notepad.exe" -Action Block'

# 创建临时PowerShell脚本文件
with tempfile.NamedTemporaryFile(mode='w', suffix='.ps1', delete=False, encoding='utf-8') as temp_script:
    temp_script.write(admin_cmd)
    temp_script_path = temp_script.name

try:
    # 获取任务原有的执行命令,用于后续恢复
    query_result = subprocess.run(
        ['schtasks.exe', '/query', '/tn', 'Powershell_Elevata', '/fo', 'list', '/v'],
        capture_output=True, text=True, check=True
    )
    original_task_action = None
    for line in query_result.stdout.splitlines():
        if line.startswith('Task To Run:'):
            original_task_action = line.split(':', 1)[1].strip()
            break

    # 修改任务动作,让高权限PowerShell静默执行临时脚本
    subprocess.run(
        [
            'schtasks.exe', '/change', '/tn', 'Powershell_Elevata',
            '/tr', f'powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -File "{temp_script_path}"'
        ],
        check=True
    )

    # 启动高权限任务
    subprocess.run(
        ['schtasks.exe', '/run', '/tn', 'Powershell_Elevata'],
        check=True
    )

    # 等待任务执行完成(根据命令复杂度调整等待时间)
    time.sleep(3)

finally:
    # 恢复任务原有的执行动作
    if original_task_action:
        subprocess.run(
            ['schtasks.exe', '/change', '/tn', 'Powershell_Elevata', '/tr', original_task_action],
            check=True
        )
    
    # 删除临时脚本文件
    if os.path.exists(temp_script_path):
        os.unlink(temp_script_path)

关键说明

  • 临时脚本:将管理员命令写入临时.ps1文件,避免命令传递时的引号转义问题
  • 静默执行:通过-WindowStyle Hidden参数让PowerShell后台运行,无窗口弹出
  • 权限绕过:添加-ExecutionPolicy Bypass确保临时脚本能被执行
  • 任务恢复:执行完成后恢复任务原有配置,不影响后续使用

内容的提问来源于stack exchange,提问作者Relok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 19:37:49