Python监控Edge版本脚本手动正常,任务计划程序系统任务运行失败排查
问题分析与解决方案
错误代码2147942401说明
该代码对应Windows系统的ERROR_ACCESS_DENIED(访问被拒绝),核心原因是系统任务使用的Local System账户无权限访问脚本中的目标路径,或脚本的路径逻辑在系统账户环境下失效。
具体修复步骤
1. 修正文件路径逻辑
脚本依赖os.path.dirname(__file__)获取目录,但系统任务默认工作目录为C:\Windows\System32,若脚本存放在用户专属目录(如C:\Users\你的用户名),Local System账户会因权限限制无法写入。建议直接指定previous_version.txt到公共可访问目录,比如C:\ProgramData(所有账户均有读写权限):
# 替换原脚本中的path和file定义 file = r"C:\ProgramData\Edge_Version_Monitor\previous_version.txt" # 先创建目标目录(不存在则自动创建) os.makedirs(os.path.dirname(file), exist_ok=True)
2. 调整任务计划程序设置
- 指定工作目录:在任务的「操作」→「编辑」面板中,设置「起始于(可选)」为脚本所在的绝对路径(如
D:\Scripts\EdgeMonitor),确保脚本路径逻辑正常。 - 启用最高权限:在任务的「安全选项」中,选择「本地系统账户」后,务必勾选「允许最高权限运行」,规避部分隐性权限限制。
- 使用绝对路径调用:启动程序选择Python的绝对路径(如
C:\Python39\python.exe),添加参数为脚本的绝对路径(如D:\Scripts\EdgeMonitor\version_check.py),禁止使用相对路径。
3. 添加异常日志排查
为脚本增加异常捕获,将错误信息写入日志,方便定位问题:
import os import win32api import traceback def local_has_changed(): try: filepath = r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" info = win32api.GetFileVersionInfo(filepath, "\\") ms = info["FileVersionMS"] new_majorversion = str(win32api.HIWORD(ms)) # 使用公共目录存储版本文件和日志 version_file = r"C:\ProgramData\Edge_Version_Monitor\previous_version.txt" log_file = r"C:\ProgramData\Edge_Version_Monitor\version_log.txt" error_log_file = r"C:\ProgramData\Edge_Version_Monitor\error_log.txt" os.makedirs(os.path.dirname(version_file), exist_ok=True) if not os.path.exists(version_file): with open(version_file, 'w+') as f: pass with open(version_file, 'r') as f: old_majorversion = str(f.read()).strip() if new_majorversion != old_majorversion: with open(log_file, 'a') as log_f: log_f.write(f'Version changed from {old_majorversion} to {new_majorversion}\n') with open(version_file, 'w') as f: f.write(str(new_majorversion)) except Exception as e: with open(error_log_file, 'a') as err_f: err_f.write(f'Error occurred: {str(e)}\n') err_f.write(traceback.format_exc() + '\n') local_has_changed()
4. 手动验证系统账户权限
借助PsTools工具的psexec命令切换到Local System账户,手动运行脚本验证:
- 下载PsTools并解压到系统路径。
- 打开命令提示符,执行
psexec -i -s cmd.exe,进入系统账户的命令行窗口。 - 在该窗口中运行Python脚本,查看是否能正常生成文件、是否有报错输出。
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

