Learn how to restart your computer (or any located in the area network) using Python in windows platforms.

Ask a geek how to fix a problem you've having with your Windows computer and they’ll likely ask "Have you tried rebooting it?". This seems like a flippant response, but rebooting a computer can actually solve many problems.

Whatever, you may have your own reasons to restart your computer, in this article we'll show you how to restart it using Python.

Requirements

  • pywin32 installed on the machine of execution.

Otherwise, you'll get the following error on your script :

ImportError: no module named win32api

To install pywin32 on your windows, go to the build repository in Source Forge here. Choose the latest build in the list (till the date of this article the 220), then the list of distributions will be shown :x86 or x64

Pywin32 source forge distributions

Install the distribution that works with your version of python and windows platform (x86 or x64).

Restarting

You may have found some solutions using the os module and executing a system shell module, the famous shutdown command :

import os
os.system("shutdown \r")

However, for some windows users this solution doesn't work correctly.

To prevent any incompatibility, we will work directly with the win32api which allow us to achieve our goal.

As mentioned in the requirements, you need to have the pywin32 installed on your machine to prevent any error at execution. 

Now, the following code provides all that you need to be able to restart the pc (and abort it if you need) using python :

# reboot.py

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(user=None,message='Rebooting', timeout=30, bForce=0, bReboot=1):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(user, 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.AbortSystemShutdown(None)
    finally:
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)

The 2 main functions will be RebootServer and AbortReboot. The AdjustPrivilege will grant the required permissions to reboot the system. Note that the RebootServer function has a timeout of 30 seconds (The computer will be restarted after 30 seconds), change it if you need to.

To restart your machine (or network computers), use the RebootServer function :

# Restart this PC (actual, as first parameter doesn't exist)
RebootServer()

# Restart the network PC named "Terminator" or the direct IP to restart it
RebootServer("Terminator")

# Restart this PC (actual) with all parameters :
# User: None 
# Message
# Time in seconds
# Force restart
# restart immediately after shutting down
# Read more about the InitiateSystemShutdown function here : https://msdn.microsoft.com/en-us/library/windows/desktop/aa376873(v=vs.85).aspx
RebootServer(None,"Be careful, the computer will be restarted in 30 seconds",30,0,1)

Rebooting dialogs windows

(Restarting warning and Reboot aborted messages)

You can test with a more dynamic example, executing the following code :

  1. Restart it in 30 seconds.
  2. Wait 10 seconds.
  3. Abort the reboot after 10 seconds.
# Reboot computer
RebootServer()
# Wait 10 seconds
time.sleep(10)
print ('Aborting shutdown')
# Abort shutdown before its execution
AbortReboot()

As the code talks by itself, now keep working in your project, have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors