Restarting PCs with Python

Have you ever wanted to restart your Windows PC with out pressing Start, Shutdown or CTRL+ALT+DEL? What about restarting your annoying co-worker’s PC…the one who just doesn’t know when to shut up? Well, Python has the answer and this blog will tell you how to do it! Note: I don’t actually recommend rebooting your neighbor’s PC at random…

Rebooting with PyWin32

Anyway, back when I was first learning about Python, I stumbled upon an ActiveState recipe on how to do this. Of course, now I can’t seem to find that recipe, but I found a similar one here: http://code.activestate.com/recipes/360649/. Thus, we’ll start with this method first and then look at a slightly different approach. If you’d like to follow along, then you’ll need to make sure you have the PyWin32 package.

or just add a host parameter to the RebootServer function and modify the InitiateSystemShutdown as necessary. If you just pass None in, then you’ll just reboot your own machine. The AdjustPrivilege method is used to change the privilege of the process so that it can actually shut the PC down. I think that only applies if you run the script as a user with limited privileges, but I almost never run that way so I can’t be sure. I do remember the recipe stating that you needed to remove the privileges that you added, which is what the finally statement is for. However, I would assume that once the reboot is complete, those privileges would have been revoked anyway.

Rebooting with just Plain Ol’ Python

The other way to initiate a shutdown is to learn the magic of your Windows command line. There is a shutdown command that you can put into your Run dialog (go to Start –> Run) that will reboot your PC too. Here’s the one I’m talking about: shutdown -r -t 1 Note that this will only restart the local machine!

Now we just need to figure out how to make Python call that for us. Probably the simplest way to do so is to import the os module and call its system method. Let’s take a look:

importosos.system("shutdown -r -t 1")

This is much shorter than the PyWin32 method, but I don’t know that it’s as robust. I used this method in a quick and dirty wxPython application I created for our Sun Ray virtual machines at work. One of the biggest problems with the Sun Ray system is that the user is connected to their virtual machine using Remote Desktop. A part of Remote Desktop is to hide the Shutdown button, so there is no simple way for the user to restart their PC unless they’re installed some kind of hotfix that does it for them. There are times when rebooting a machine is a good thing, so I took the script above and put it into the following application:

I looked at a lot of icons for this project and I think I ended up just doing searches for shutdown and logout icons and downloaded the ones I liked the best. Both of these free or had Creative Commons licenses.

Now you know the tricks to restart local and remote machines. Use this knowledge wisely!