O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sample Code to Reboot the Current Machine

You now have the knowledge to successfully make a win32api.Initiate-SystemShutdown() call.

The code obtains the necessary privileges to reboot the machine, then makes the call to win32api.InitiateSystemShutdown(). Unfortunately, the dialog displayed by Windows NT doesn’t include any way to disable the shutdown operation. Once the shutdown has begun, the only way to stop it is programmatically.

To cater to this, the sample application, shown in the following code, initiates a shutdown with a 30-second delay. The code then sleeps for 10 seconds before programmatically aborting the shutdown using win32api.AbortSystem-Shutdown() . If you refer to the Windows NT documentation or Appendix B, you’ll notice that this function requires the same privileges needed to initiate the shutdown in the first place. So before aborting the shutdown, you must jump through the same privilege hoops. To assist the process, let’s move the code that manages the privileges to a helper function that should be suitable for managing any type of privilege:

# RebootServer.py - Reboots a remove server 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. id = win32security.LookupPrivilegeValue(None, priv) # Now ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required