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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access