[python-win32] rebooting windows from Python?

Tim Golden mail at timgolden.me.uk
Fri Dec 5 10:02:10 CET 2008


Tim Roberts wrote:
> Alec Bennett wrote:
>> I'm wondering if there's some way to reboot or shutdown Windows from within Python? 
>>
>> I can log out like this:
>>
>> win32api.ExitWindowsEx(4)
>>
>> And according to the documentation, I should be able to shutdown like this:
>>
>> win32api.ExitWindowsEx(2)
>>
>> But that returns the following error:
>>
>> 'A required privilege is not held by the client.'
>>
>> Is there some way to do this? Currently I'm running shutdown.exe, which works, but I'd rather do it directly if possible.
>>   
> 
> Yes -- you have to acquire the required privilege.  ;)  The mechanism to
> do so is tedious, and involves fetching your current privilege token,
> then adjusting it in place.  You can read about it in the MSDN page on
> ExitWindowsEx:
>     http://msdn.microsoft.com/en-us/library/aa376868.aspx
> 
> Personally, and it really is a personal preference, I think it's a lot
> less trouble, and a lot easier to understand, just to use the tools at
> my disposal:
>     subprocess.call( "shutdown", "-r" )
> 

Or... WMI makes this one slightly easier. This example:

 http://timgolden.me.uk/python/wmi_cookbook.html#reboot_remote_machine

comes close. You don't -- probably -- need the remote machine bit,
and the privilege you need is Shutdown, not RemoteShutdown. Oh, sod
it; here's the code:

<code>
import wmi

wmi.WMI (privileges=["Shutdown"]).Win32_OperatingSystem ()[0].Shutdown ()

</code>

TJG



More information about the python-win32 mailing list