暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python 实现 Windows 关机、重启

生有可恋 2022-10-31
3501

默认的关机重启操作可以调用系统提供的命令行接口,即 shutdown 程序。也可以调用 Windows 的 API 接口。

调用 shutdown 的实现:

    import os
    # 关机
    os.system("shutdown -s -t 0 ")
    # 重启
    os.system("shutdown -r -t 0 ")

    调用 Windows API 的实现:

      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)


      #test the functions:


      # Reboot computer
      RebootServer()


      # shutdown
      RebootServer(None'Shutdown'3000)


      # Abort shutdown before its execution
      AbortReboot()

      在测试以上代码前先安装 pywin32 模块:

        pip install pywin32

        这里调用的是 pywin32 中封装好的 Windows API,其中所调用的关机指令为 win32api.InitiateSystemShutdown。因为 NT 内核提高了安全性,在执行前一定要获取到相应的权限,这里调用 AdjustPrivilege 就是为了获取关机权限,并且需要使用管理员权限执行脚本。

        如果直接调用 win32api.InitiateSystemShutdown 将会报错:

          >>> win32api.InitiateSystemShutdown(user, message, timeout, bForce, bReboot)
          Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
          pywintypes.error: (5, 'InitiateSystemShutdown', '拒绝访问。')

          提示拒绝访问,这里就算是以管理员权限执行一样会提示拒绝访问。在执行前需要调用 win32security 获取关机权限。以上代码来自 stackoverflow,当更改 win32api.InitiateSystemShutdown 的参数后可以用来控制关机或重启,并且可以设置延时、是否强制执行。

          • https://stackoverflow.com/questions/65212958/how-to-reboot-remote-desktop-using-python-script


          函数 win32api.InitiateSystemShutdown 的参数说明为:

          InitiateSystemShutdown(computerName, message, timeOut, bForceClose, bRebootAfterShutdown)

          • 函数作用:触发一次关机或重启操作

          • computerName : string/PyUnicode  当为None指本机

          • message : string/PyUnicode 提示信息

          • timeOut : int    延迟(秒)

          • bForceClose : int  是否强制关机,1 强制,0 不强制

          • bRebootAfterShutdown : int 关机后是否重启, 1 重启 ,0 关机


          参考:

          • http://timgolden.me.uk/pywin32-docs/win32api__InitiateSystemShutdown_meth.html

          • https://github.com/VFPX/Win32API/blob/master/libraries/advapi32/InitiateSystemShutdown.md

          • https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-initiatesystemshutdowna


          全文完。

          如果转发本文,文末务必注明:“转自微信公众号:生有可恋”。


          文章转载自生有可恋,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

          评论