[python-win32] rebooting windows from Python?

Mike Driscoll mdriscoll at co.marshall.ia.us
Fri Dec 5 15:40:32 CET 2008


Alec,

> And thus I say for the second time in 24 hours: Eureka!
>
> For anyone else coming down this path, here's how to shutdown, reboot or logoff Windows, each with the option to force the action. In other words, you can force Windows to reboot even if its asking if you want to save a document. 
>
> <code>
>
> nLogOff=0 
> nReboot=2 
> nForceLogOff=4 
> nForceReboot=6 
> nPowerDown=8 
> nForcePowerDown=12
>
> import wmi
> wmi.WMI(privileges=["Shutdown"]).Win32_OperatingSystem()[0].Win32Shutdown (Flags=nForceReboot)
>
> </code>
>
> As is probably pretty obvious, change the "Flags" parameter to whatever you want from the list of options above.
>
> On the off chance anyone's curious what my questions have been about, its a sleep timer to shutdown winamp, itunes, vlc, etc., or shutdown windows after a period of time. So now I can be a total slacker and fall asleep to a DVD and not have the menu music playing all night long.
>
> http://gizmoware.net/sleeper
>
>   

I've been using the following method that I found on ActiveState's 
Cookbook, which I modified a little 
(http://code.activestate.com/recipes/360649/):

<code>

import win32security
import win32api
import sys
import time
from ntsecuritycon import *

def AdjustPrivilege(priv, enable=1):
    # Get the process token
    flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY
    htoken = 
win32security.OpenProcessToken(win32api.GetCurrentProcess(), flags)
    # Get the ID for the system shutdown privilege.
    idd = win32security.LookupPrivilegeValue(None, priv)
    # Now obtain the privilege for this process.
    # Create a list of the privileges to be added.
    if enable:
        newPrivileges = [(idd, SE_PRIVILEGE_ENABLED)]
    else:
        newPrivileges = [(idd, 0)]
    # and make the adjustment
    win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)

def RebootServer(message='Rebooting', timeout=30, bForce=0, bReboot=1):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(None, message, timeout, bForce, 
bReboot)
    finally:
        # Now we remove the privilege we just added.
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)

def AbortReboot():
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.AbortSystemShotdown(None)
    finally:
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)

if __name__ == '__main__':
    RebootServer()
    time.sleep(10)
    print 'Aborting shutdown'
    AbortReboot()

</code>

Tim Roberts mentioned it, but didn't give any code. I use it for some of 
my unattended installs where I need to reboot the PC at certain points 
to continue the installation. Golden's method is definitely shorter and 
clearer though.

Mike


More information about the python-win32 mailing list