2017-09-02 70 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的這類問題。 –

相關問題