PYTHON | 阻止用户终止进程
这里提到了一种非常酷的功能:
有没有人知道怎么把这段C++代码翻译成Python,或者修改一下让它至少能在C/C++中编译(假设它确实是C/C++代码):
static const bool ProtectProcess()
{
HANDLE hProcess = GetCurrentProcess();
EXPLICIT_ACCESS denyAccess = {0};
DWORD dwAccessPermissions = GENERIC_WRITE|PROCESS_ALL_ACCESS|WRITE_DAC|DELETE|WRITE_OWNER|READ_CONTROL;
BuildExplicitAccessWithName( &denyAccess, _T("CURRENT_USER"), dwAccessPermissions, DENY_ACCESS, NO_INHERITANCE );
PACL pTempDacl = NULL;
DWORD dwErr = 0;
dwErr = SetEntriesInAcl( 1, &denyAccess, NULL, &pTempDacl );
// check dwErr...
dwErr = SetSecurityInfo( hProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, pTempDacl, NULL );
// check dwErr...
LocalFree( pTempDacl );
CloseHandle( hProcess );
return dwErr == ERROR_SUCCESS;
}
2 个回答
1
你可以试试用 ctypes。另外,你也可以看看 pywin32。还有一个选择是 IronPython。如果你用的是ActivePython,可以参考 win32api。
另外,我不太清楚你想要实现这个的原因,这可能意味着还有其他更优雅的解决方案可以考虑。
2
这里有一个比较粗糙的ctypes代码翻译,跟你发的代码差不多。看起来它还真的能工作!需要注意的是,我去掉了对CloseHandle
的调用,因为那是错误的。你不应该对伪句柄调用CloseHandle
,而GetCurrentProcess
返回的就是伪句柄。
from ctypes import *
from ctypes.wintypes import *
from win32con import *
class TRUSTEE(Structure):
pass
TRUSTEE._fields_ = (
('pMultipleTrustee', POINTER(TRUSTEE)),
('MultipleTrusteeOperation', c_int),
('TrusteeForm', c_int),
('TrusteeType', c_int),
('ptstrName', LPSTR)
)
class EXPLICIT_ACCESS(Structure):
_fields_ = (
('grfAccessPermissions', DWORD),
('grfAccessMode', c_int),
('grfInheritance', DWORD),
('Trustee', TRUSTEE)
)
GetCurrentProcess = windll.kernel32.GetCurrentProcess
GetCurrentProcess.restype = HANDLE
hProcess = GetCurrentProcess()
denyAccess = EXPLICIT_ACCESS()
dwAccessPermissions = DWORD(GENERIC_WRITE|PROCESS_ALL_ACCESS|WRITE_DAC|DELETE|WRITE_OWNER|READ_CONTROL);
BuildExplicitAccessWithName = windll.advapi32.BuildExplicitAccessWithNameA
BuildExplicitAccessWithName.restype = None
DENY_ACCESS = 3
NO_INHERITANCE = 0
BuildExplicitAccessWithName(byref(denyAccess), 'CURRENT_USER', dwAccessPermissions, DENY_ACCESS, NO_INHERITANCE)
SetEntriesInAcl = windll.advapi32.SetEntriesInAclA
SetEntriesInAcl.restype = DWORD
SetEntriesInAcl.argtypes = (ULONG, POINTER(EXPLICIT_ACCESS), c_voidp, POINTER(c_voidp))
pTempDacl = c_voidp()
dwErr = SetEntriesInAcl(1, byref(denyAccess), None, byref(pTempDacl));
SetSecurityInfo = windll.advapi32.SetSecurityInfo
SetSecurityInfo.restype = DWORD
SetSecurityInfo.argtypes = (HANDLE, c_int, DWORD, c_voidp, c_voidp, c_voidp, c_voidp)
SE_KERNEL_OBJECT = 6
dwErr = SetSecurityInfo(hProcess, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, None, None, pTempDacl, None);
LocalFree = windll.kernel32.LocalFree
LocalFree.restype = c_voidp
LocalFree.argtypes = (c_voidp,)
LocalFree(pTempDacl)