2017-09-02 68 views
0

才能运行具有管理员权限的脚本,我使用ctypes.windll.shell32.ShellExecuteW。我不想用win32api,因为这是一个需要安装,其中​​不包。我已经意识到,使用下面的脚本(简体),如果脚本是在一个目录中运行在一个空格(如“C:\用户\用户\ Documents \我的文件夹”),即使UAC请求被批准,该脚本不会获得管理员权限。只要脚本没有在名称中有空格的目录中执行,它就可以正常工作。为什么Python UAC Request不适用于其中有空格的路径?

脚本:

# Name of script is TryAdmin.py 
import ctypes, sys, os 

def is_admin(): 
    try: 
     return ctypes.windll.shell32.IsUserAnAdmin() 
    except: 
     return False 


if is_admin(): 
    print("I'm an Admin!") 
    input() 
else: 
    b=ctypes.windll.shell32.ShellExecuteW(None,'runas',sys.executable,os.getcwd()+'\\TryAdmin.py',None,1) 

if b==5: # The user denied UAC Elevation 

    # Explain to user that the program needs the elevation 
    print("""Why would you click "No"? I need you to click yes so that I can 
have administrator privileges so that I can execute properly. Without admin 
privileges, I don't work at all! Please try again.""") 
    input() 

    while b==5: # Request UAC elevation until user grants it 
     b=ctypes.windll.shell32.ShellExecuteW(None,'runas',sys.executable,os.getcwd()+'\\TryAdmin.py',None,1) 

     if b!=5: 
      sys.exit() 
     # else 
     print('Try again!') 
     input() 
else: 
    sys.exit() 
+0

这有什么错SYS? –

回答

1

这个问题ShellExecute: Verb "runas" does not work for batch files with spaces in path是相似的,但在C++中。

它有可能的原因您的问题,涉及到的问题引用一个很好的解释。

如果引用参数(或至少第二个),你应该解决这个问题。

b=ctypes.windll.shell32.ShellExecuteW(
    None, 'runas', 
    '"' + sys.executable + '"', 
    '"' + os.getcwd() + '\\TryAdmin.py' + '"', 
    None, 1) 
+0

谢谢。我认为它与某些语言处理路径/引号的方式有关,因为知道批处理需要在间隔路径附近引用引号。事实上,我尝试了一些引用,但我显然没有尝试正确的组合。我很不高兴,我花了50代表,结果是一个简单的解决方案,但至少我现在知道了。我很惊讶,无处可以找到有关Python的这类问题。 –

相关问题