Darshan
Darshan

Reputation: 131

Programmatically shutdown remote machine in Winapi

How would I go about shutting down or rebooting a system which is in same LAN, assuming I have all the necessary privileges.

Please see the code below

OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, 
                     &tokenHandle);

    LookupPrivilegeValue("Computer name", SE_REMOTE_SHUTDOWN_NAME, 
                         &tokenPrivileges.Privileges[0].Luid);

    tokenPrivileges.PrivilegeCount = 1;
    tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    AdjustTokenPrivileges(tokenHandle, FALSE, &tokenPrivileges, 0, 
                         0, 0);

    switch(action)
    {
    default:
    case constEWXReboot:
    case constEWXRestartApps:
        if (!InitiateSystemShutdownEx("Computer name","Remote machine shutdown", 10, TRUE, TRUE, SHTDN_REASON_MAJOR_APPLICATION))
        {
            ErrGen(constErrCannotRestartSystem);
        }
        break;

I am getting error code #53 The network path was not found. Please suggest me where i am going wrong here.

Upvotes: 0

Views: 829

Answers (2)

Jovibor
Jovibor

Reputation: 789

InitiateSystemShutdownEx win API function will do this.

Initiates a shutdown and optional restart of the specified computer, and optionally records the reason for the shutdown.

To shut down the local computer, the calling thread must have the SE_SHUTDOWN_NAME privilege. To shut down a remote computer, the calling thread must have the SE_REMOTE_SHUTDOWN_NAME privilege on the remote computer. By default, users can enable the SE_SHUTDOWN_NAME privilege on the computer they are logged onto, and administrators can enable the SE_REMOTE_SHUTDOWN_NAME privilege on remote computers.

Upvotes: 4

Paul R
Paul R

Reputation: 213200

You don't need to use an API - you can just invoke shutdown.exe via a call to system(), e.g.:

system("shutdown -r -f -t 00 -m \\\\computername");

Upvotes: 0

Related Questions