pywin32重启电脑

最近一直忙着乱七八糟的事,还做了几天义工,没怎么写程序
今天打算用PYTHON来做个WIN32下的定时重启功能来限制弟弟玩游戏
看了下PYTHON原生的,可以通过命令行来调用shutdown命令,但PYWIN32这个库可以让用户直接调用WIN32 API,给力。
于是看看API吧

找到了这个API:

 

InitiateSystemShutdown

MSDN中已经给出了详细的说明 ,我就不多说了
MSDN中也给出个例子,需要注意的是,需要在使用这个函数前要提升进程的权限,否则会出这个问题:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
error: (5, 'InitiateSystemShutdown', '\xbe\xdc\xbe\xf8\xb7\xc3\xce\xca\xa1\xa3')
最开始我也没注意到,后来在个英文网页找到了答案:

 

http://book.opensourceproject.org.cn/lamp/python/pythonwin/opensource/pythonwin32_snode127.html

里面也有pywin32实现reboot的源码,可以拿来直接用(测试环境:XP SP3)
怕有些朋友不方便,我把代码贴出吧:

代码
#!/usr/bin/env python
#
 -*- coding: utf-8 -*-
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.
    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 RebootServer(message="Server Rebooting", timeout=30, bForce=0, bReboot=1):
    AdjustPrivilege(SE_SHUTDOWN_NAME)
    
try:
        win32api.InitiateSystemShutdown(None, 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:
        
# Now we remove the privilege we just added.
        AdjustPrivilege(SE_SHUTDOWN_NAME, 0)
            
if __name__=='__main__':
        message 
= "This server is pretending to reboot\r\n"
        message 
= message + "The shutdown will stop in 10 seconds"
        RebootServer(message)
        
print "Sleeping for 10 seconds"
        time.sleep(
10)
        
print "Aborting shutdown"
        AbortReboot()



 

posted @ 2011-01-29 01:14  飘啊飘  阅读(1644)  评论(1编辑  收藏  举报