Knowledge Base Nr: 00054 Remote_Shutdown_Set_Privilege.cpp - http://www.swe-kaiser.de

Downloads:

shutdown eines computers im netz (oder eigener) mittels ::InitiateSystemShutdown()
setzen von security privileges (wie in useradmin)

  
BOOL Shutdown(LPCSTR lpszMachine, DWORD nWaitSec, BOOL bReboot, BOOL bCloseApps)
{
BOOL bSuccess;

if (lpszMachine) //remote shutdown
bSuccess = SetPrivilege(SE_REMOTE_SHUTDOWN_NAME, TRUE); // to enable or disable privilege
else
bSuccess = SetPrivilege(SE_SHUTDOWN_NAME, TRUE); // to enable or disable privilege

bSuccess = ::InitiateSystemShutdown((LPSTR)lpszMachine, // pointer to name of computer to shut down
"Die Maschine wird jetzt heruntergefahren! :-)", // pointer to message to display in dialog box
nWaitSec, // time to display dialog box in seconds
bCloseApps, // force applications closed flag
bReboot // reboot flag
);
DWORD dwRes = ::GetLastError();

return (dwRes == ERROR_SUCCESS);
}

BOOL SetPrivilege(LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege) // to enable or disable privilege
{
HANDLE hToken = 0; // access token handle
if (!OpenProcessToken(::GetCurrentProcess(), // handle to process
TOKEN_ADJUST_PRIVILEGES, // access to process
&hToken)) // pointer to handle to open access token
{
TRACE("OpenProcessToken failed: %u\n", GetLastError() );
return FALSE;
}

TOKEN_PRIVILEGES tp;
LUID luid;
if ( !LookupPrivilegeValue(NULL, // lookup privilege on local system
lpszPrivilege, // privilege to lookup
&luid ) )
{ // receives LUID of privilege
TRACE("LookupPrivilegeValue error: %u\n", GetLastError() );
return FALSE;
}

tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;

if (bEnablePrivilege)
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
else
tp.Privileges[0].Attributes = 0;

// Enable the privilege or disable all privileges.
AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES)
, (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL);

// Call GetLastError to determine whether the function succeeded.
if (GetLastError() != ERROR_SUCCESS)
{
TRACE("AdjustTokenPrivileges failed: %u\n", GetLastError() );
return FALSE;
}

return TRUE;
}