如何在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
相关产品推荐
相关产品推荐

