// сие есть плод моих медитаций над MSDN :-)
#include "stdafx.h" // если проект сгенерен в MSVC по дефолту
#include <stdio.h>
#include <process.h>
#include <string.h>
#include <windows.h>
#include <conio.h>
BOOL SetPrivilege(
HANDLE hToken, // access token handle
LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege // to enable or disable privilege
);
int die(char * str,int retval){fputc('\n',stdout);fputs(str,stdout);exit(retval);return 0;};
int main(int argc, char* argv[])
{
char mname[1024];
HANDLE hndl;
char bWhatToDo='r';
if (argc < 2){
puts("Enter machine name>");
gets(mname);
label1:
puts("reboot or shutdown or quit[r/s/q]?");
bWhatToDo=tolower(bWhatToDo);
if((bWhatToDo=getc(stdin))=='q')die("finishing",-1);
if((bWhatToDo!='r')&&(bWhatToDo!='s'))goto label1;
}
else{
strncpy(mname,argv[1],1023);
bWhatToDo=tolower(argv[2][0]);
printf("Relax for a moment whilst rebooting machine '%s'...",mname);
}
/*
printf("bWhatToDo flag =%c",bWhatToDo);
exit(1);
*/
if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,&hndl))
die("call to openprocesstoken failed",3);
SetPrivilege(hndl,SE_SHUTDOWN_NAME,TRUE);
if(!InitiateSystemShutdown(
mname, // pointer to name of computer to shut down
"Message from Administrator:\n Выключаю этот компьютер :)", // pointer to message to display in
// dialog box
20, // time to display dialog box
TRUE, // force applications closed flag
(bWhatToDo=='r') // reboot flag
)
)
{
strcat(mname,":Failed to InitiateSystemShutdown!");
die(mname,4);
}
else puts("\nSuccess. Enjoy!");
return 1;
};
//////////////////////////////////////
/////////////////////////////////////
BOOL SetPrivilege(
HANDLE hToken, // access token handle
LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege // to enable or disable privilege
)
//...................................
{
TOKEN_PRIVILEGES tp;
LUID luid;
if ( !LookupPrivilegeValue(
NULL, // lookup privilege on local system
lpszPrivilege, // privilege to lookup
&luid ) ) { // receives LUID of privilege
printf("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) {
printf("AdjustTokenPrivileges failed: %u\n", GetLastError() );
return FALSE;
}
return TRUE;
}
---
теперь замечание: программа работает только в WinNT4.0/2000 :(
принципиально не пишу программ под win9x :))
для ее успешного запуска нужны привилегии power user'а.
с наилучшими пожеланиями,
йцукенг.
|