个性化阅读
专注于IT技术分析

如何在Windows中使用Python重新启动本地或网络计算机

点击下载

本文概述

询问一个极客如何解决Windows计算机上的问题, 他们可能会问”你是否尝试过重新启动它?”。这似乎是一种轻率的响应, 但是重新启动计算机实际上可以解决许多问题。

无论如何, 你都有自己的理由来重启计算机, 在本文中, 我们将向你展示如何使用Python重启计算机。

要求

  • pywin32安装在执行的机器上。

否则, 你将在脚本中收到以下错误:

ImportError: no module named win32api

要在Windows上安装pywin32, 请转到此处的Source Forge中的构建存储库。在列表中选择最新版本(到本文的日期为220), 然后将显示分发列表:x86或x64

Pywin32 Source Forge发行版

安装与你的python和Windows平台版本(x86或x64)兼容的发行版。

重新开始

你可能已经找到了使用os模块并执行系统外壳模块的一些解决方案, 这是著名的shutdown命令:

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

但是, 对于某些Windows用户, 此解决方案无法正常工作。

为避免任何不兼容, 我们将直接与win32api合作, 这将使我们实现目标。

如需求中所述, 你需要在计算机上安装pywin32, 以防止执行时出错。

现在, 以下代码提供了使用python重新启动pc(并在需要时中止它)所需的一切:

# 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)

2个主要功能是RebootServer和AbortReboot。 AdjustPrivilege将授予所需的权限以重新引导系统。请注意, RebootServer功能的超时时间为30秒(计算机将在30秒后重新启动), 请根据需要进行更改。

要重新启动计算机(或网络计算机), 请使用RebootServer函数:

# 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)
重新启动对话框窗口

(重新启动警告并重新启动中止的消息)

你可以使用更动态的示例进行测试, 执行以下代码:

  1. 30秒后重新启动。
  2. 等待10秒钟。
  3. 10秒后中止重新启动。
# Reboot computer
RebootServer()
# Wait 10 seconds
time.sleep(10)
print ('Aborting shutdown')
# Abort shutdown before its execution
AbortReboot()

正如代码本身所说的那样, 现在继续在你的项目中工作, 玩得开心!

赞(0)
未经允许不得转载:srcmini » 如何在Windows中使用Python重新启动本地或网络计算机

评论 抢沙发

评论前必须登录!