OpenProcess使用PROCESS_ALL_ACCESS返回ERROR_ACCESS_DENIED

原文地址

http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/eeb93be6-872c-4028-b0ae-cd873e089825

 

Rajeesh... _

Rajeesh... _

Ness technologies

280 Points 5 0 0
Recent Achievements
First Helpful Vote Forums Replies I Forums Answerer I
Ness technologies

280 Points

   Answered
I just went through OpenProcess API in msdn, it says below for for PROCESS_ALL_ACCESS. I think this was the issue which you were facing.

Windows Server 2003 and Windows XP/2000:   The size of the PROCESS_ALL_ACCESS flag increased on Windows Server 2008 and Windows Vista. If an application compiled for Windows Server 2008 and Windows Vista is run on Windows Server 2003 or Windows XP/2000, the PROCESS_ALL_ACCESS flag is too large and the function specifying this flag fails with ERROR_ACCESS_DENIED. To avoid this problem, specify the minimum set of access rights required for the operation. If PROCESS_ALL_ACCESS must be used, set _WIN32_WINNT to the minimum operating system targeted by your application (for example,#define _WIN32_WINNT _WIN32_WINNT_WINXP). For more information, seeUsing the Windows Headers .

 

Windows Server 2008及Windows Vista上PROCESS_ALL_ACCESS的标志有所增加,如果应用程序编译时的target OS是Windows Server 2008或Windows Vista, 但却运行在Windows Server 2003或Windows XP/2000上,PROCESS_ALL_ACCESS太大,指定这个标志的函数会返回ERROR_ACCESS_DENIED错误。如果避免这个错误,指定操作所需的最小访问权限,而不是图省事指定PROCESS_ALL_ACCESS. 如果必须要用PROCESS_ALL_ACCESS, 要在程序中定义_WIN32_WINNT _WIN32_WINNT_WINXP

import psutil import ctypes import sys from ctypes import wintypes # 设置权限常量 PROCESS_ALL_ACCESS = 0x1F0FFF # 优先级常量 IDLE_PRIORITY_CLASS = 0x40 BELOW_NORMAL_PRIORITY_CLASS = 0x4000 NORMAL_PRIORITY_CLASS = 0x20 ABOVE_NORMAL_PRIORITY_CLASS = 0x8000 HIGH_PRIORITY_CLASS = 0x80 REALTIME_PRIORITY_CLASS = 0x100 # 优先级映射,包含友好名称 PRIORITY_MAP = { 'idle': (IDLE_PRIORITY_CLASS, '空闲'), 'belownormal': (BELOW_NORMAL_PRIORITY_CLASS, '低于正常'), 'normal': (NORMAL_PRIORITY_CLASS, '正常'), 'abovenormal': (ABOVE_NORMAL_PRIORITY_CLASS, '高于正常'), 'high': (HIGH_PRIORITY_CLASS, '高'), 'realtime': (REALTIME_PRIORITY_CLASS, '实时') } def get_process_handle(pid): """获取进程句柄""" kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) handle = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid) if not handle: raise ctypes.WinError(ctypes.get_last_error()) return handle def set_process_priority(pid, priority_class): """设置进程优先级""" try: # 获取进程句柄 handle = get_process_handle(pid) # 设置优先级 kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) result = kernel32.SetPriorityClass(handle, priority_class) if not result: raise ctypes.WinError(ctypes.get_last_error()) # 关闭句柄 kernel32.CloseHandle(handle) return True, None except Exception as e: return False, str(e) def find_process_by_name(process_name): """根据进程名查找PID""" pids = [] # 处理进程名,支持带或不带.exe后缀 if not process_name.lower().endswith('.exe'): process_name += '.exe' for proc in psutil.process_iter(['pid', 'name']): try: if proc.info['name'].lower() == process_name.lower(): pids.append(proc.info['pid']) except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass return pids def get_user_input(): """获取用户输入""" print("=== Windows 进程优先级修改工具 ===") print() # 获取进程名 process_name = input("请输入要修改的进程名(例如:notepad 或 notepad.exe):").strip() if not process_name: print("错误:进程名不能为空!") sys.exit(1) # 显示优先级选项 print("\n可用的优先级选项:") for key, (value, desc) in PRIORITY_MAP.items(): print(f" {key} - {desc}") print("注意:realtime(实时)优先级请谨慎使用!") # 获取优先级选择 while True: priority_choice = input("\n请输入优先级类型:").strip().lower() if priority_choice in PRIORITY_MAP: break print(f"错误:无效的优先级类型!请从 {', '.join(PRIORITY_MAP.keys())} 中选择。") return process_name, priority_choice def main(): # 检查管理员权限 try: if not ctypes.windll.shell32.IsUserAnAdmin(): # 重新以管理员身份运行 ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1) sys.exit(0) except Exception as e: print("错误:需要管理员权限才能修改进程优先级!") input("按回车键退出...") sys.exit(1) # 获取用户输入 process_name, priority_choice = get_user_input() # 获取优先级值和描述 priority_class, priority_desc = PRIORITY_MAP[priority_choice] # 查找进程 pids = find_process_by_name(process_name) if not pids: print(f"\n错误:未找到进程 '{process_name}'!") input("按回车键退出...") return print(f"\n找到 {len(pids)} 个进程实例:") for pid in pids: print(f" PID: {pid}") # 确认修改 confirm = input(f"\n确定要将这些进程的优先级设置为 '{priority_desc}' 吗?(y/n):").strip().lower() if confirm not in ['y', 'yes']: print("操作已取消。") input("按回车键退出...") return # 修改优先级 success_count = 0 fail_count = 0 print("\n开始修改优先级...") for pid in pids: success, error = set_process_priority(pid, priority_class) if success: print(f"✓ 进程ID {pid} 优先级修改成功!") success_count += 1 else: print(f"✗ 进程ID {pid} 优先级修改失败:{error}") fail_count += 1 # 输出总结 print("\n=== 操作完成 ===") print(f"成功修改:{success_count} 个进程") print(f"修改失败:{fail_count} 个进程") if success_count > 0: print("\n✅ 优先级修改任务成功完成!") else: print("\n❌ 优先级修改任务执行失败!") input("\n按回车键退出...") if __name__ == "__main__": main()我说每一个代码你干嘛讲一个部分呢?
最新发布
11-27
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值