Fog Creek Software
Discussion Board




Shutting down Windows with Code

Sorry - might be off topic, but the sites _with_ code don't seem to adress this problem:

I have a Virtual Maschine set up to do my Daily Build. It gets startet by a Scheduled Task on a Server. The VM is set up (also with Task Scheduler) to start the build script (VBScript / Python) and, when its done, to run following code (basically - I have removed the commandline interface being used:

<-- Code in next post -->

When I log on to the VM and start the script manualy, everything just works fine. If I start the VM and log in (remember: Task Scheduler starts the script on system start) then the script runs as well, poweroff at the end.

Now: If I don't log on, the script runs (I know, because the server beeps and I get an email sent to me at the end with all the failed builds), but THE VM DOESN'T POWEROFF!

I also don't get any errors, nothing!

DarenThomas
Tuesday, February 17, 2004

import sys
import win32api
from win32security import *

#Constants for the shutdown function
LOGOFF          = 0
SHUTDOWN        = 1
REBOOT          = 2
FORCE          = 4
POWEROFF        = 8
FORCEIFHUNG    = 10

def acquirePermission():
    """acquire permission to shutdown the system"""
    process = win32api.GetCurrentProcess()
    token = OpenProcessToken(process, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY)
    luid = LookupPrivilegeValue(None, "SeShutdownPrivilege")
    AdjustTokenPrivileges(token, False, [(luid, SE_PRIVILEGE_ENABLED)])

def shutdown(mode=SHUTDOWN):
    """ shutdown the computer with mode <mode>.
        mode can be one of following values:
   
        * LOGOFF(0) - log off the user from the system
   
        * SHUTDOWN(1) - shutdown the pc (without poweroff)
   
        * REBOOT(2) - reboot the pc
   
        * POWEROFF(8) - shutdown pc and poweroff if supported by hardware
   
        These can be combined with FORCE(4) or FORCEIFHUNG(10).
    """
    acquirePermission()
    win32api.ExitWindowsEx(mode)
   

if __name__ == '__main__':
  shutdown(POWEROFF | FORCE)

DarenThomas
Tuesday, February 17, 2004

Since you know that there's a problem it might be a good idea to actually check those values you get back from your Win32 calls, and call GetLastError if something unexpected happens.

My guess: you are logged in as someone who has shutdown privilege (probably admin) so the script works. But whatever user runs the script elsewhere doesn't have that privilege. Ergo, nothing happens. (You can't programmatically exceed user privileges!)

Chris Nahr
Tuesday, February 17, 2004

*  Recent Topics

*  Fog Creek Home