C++ Windows XP的远程关机实现

14年前

//参数一:要关机的远程机器的IP或者主机名

//参数二:关机提示信息

//参数三:关机等待时间,单位为秒

//参数四:关机后是否启动主机(重启)

 

BOOL shutdownHost(CString hostName,CString shutdownInfo,int dwTimeout,BOOL isRebootAfterShutdown) {

     HANDLE hToken;

     TOKEN_PRIVILEGES tkp;

     BOOL fResult; // system shutdown flag

     if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)){

         fResult = FALSE;

         return fResult;

     }

     LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

     tkp.PrivilegeCount = 1; // one privilege to set

     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

     AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);

     if (GetLastError() != ERROR_SUCCESS){

         fResult = FALSE;

         return fResult;

     }

     fResult=InitiateSystemShutdown(CStringCovertLPTSTR(hostName), CStringCovertLPTSTR(shutdownInfo), dwTimeout, TRUE, isRebootAfterShutdown);

     if (!fResult)

     {

         return fResult;

     }

     tkp.Privileges[0].Attributes = 0;

     AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);

     if (GetLastError() != ERROR_SUCCESS)

     {

         fResult = FALSE;

         return fResult;

     }

     return fResult;

}

 

 

LPTSTR CStringCovertLPTSTR(CString str){

     LPTSTR lpszText = new TCHAR[str.GetLength()+1];

     lstrcpy( lpszText, str );

     return lpszText;

}