2012年8月20日 星期一

Python Shutdown / Reboot / Logout / Lock Windows machine

Shutdown / Reboot
import win32api
import win32security
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 obtain the privilege for this process.
    # Create a list of the privileges to be added.
    if enable:
        newPrivileges = [(id, SE_PRIVILEGE_ENABLED)]
    else:
        newPrivileges = [(id, 0)]
    # and make the adjustment.
    win32security.AdjustTokenPrivileges(htoken, 0, newPrivileges)
def Halt(sec = 1):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(None, "System will shutdown.", sec, 1, 0)  # lpMachineName, lpMessage, dwTimeout, bForceAppsClosed, bRebootAfterShutdown
    finally:
        # Now we remove the privilege we just added.
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)

def Reboot(sec = 1):
    #subprocess.Popen('shutdown -r -t %s -c "System will reboot."' % (sec),
    #        stdout=subprocess.PIPE).communicate()[0]
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    try:
        win32api.InitiateSystemShutdown(None, 'System will reboot.', sec, 1, 1)  # lpMachineName, lpMessage, dwTimeout, bForceAppsClosed, bRebootAfterShutdown
    finally:
        # Now we remove the privilege we just added.
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)        

Logout
import ctypes
ctypes.windll.user32.ExitWindowsEx(0, 1)

Lock  
import ctypes
ctypes.windll.user32.LockWorkStation()




Reference :
Windows關機函數ExitWindowsEx使用大全(适用Windows所有操作平台) - Windows SDK/API - Delphi - 程式代碼集
InitiateSystemShutdown function
logout - Windows logoff using Python - Stack Overflow
Logout or switch user in Windows using Python - Stack Overflow

沒有留言:

張貼留言