2013-12-17 42 views
2

我有一個我寫的python函數,它可以使用子進程作爲root運行shell命令。我試圖添加功能來檢測不正確的密碼嘗試。這是功能。以root身份運行shell命令並使用python檢測密碼嘗試失敗

local_pass = None 

def runShellCommandAsRoot(cmd): 
    global local_pass 
    if local_pass == None: 
     print "Enter admin user's password." 
     local_pass = getpass.getpass() 

    cmd = "echo {} | sudo -S {}".format(local_pass, cmd) 
    sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    out, err = sp.communicate() 

這工作正常。我試圖添加來檢測失敗的密碼嘗試解析stderr,但我會在每個循環中得到不同的結果。見下面(這個我試過加入上面的函數)代碼:

for i in range(5): 
    if err == "Password:Sorry, try again.\nPassword:\nsudo: 1 incorrect password attempt\n": 
     print "Enter admin user's password." 
     local_pass = getpass.getpass() 
     cmd = "echo {} | sudo -S {}".format(local_pass, cmd) 
     sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
     out, err = sp.communicate() 
    elif err == None or err == "": 
     return out, err 
     break 
    if i == 4: 
     print "Exceeded password attempts." 
     exit() 
+0

不應該sudo日誌已經這樣嗎? –

回答

1

朋友幫我找出一個更好的解決方案來運行shell命令,也包括錯誤檢查用戶的密碼!見下:

def run_shell_command_as_root(cmd): 
    cmd[:0] = ['sudo'] 
    if not authenticate(): 
     print 'Unable to authenticate' 
     sys.exit(1) 
    sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    return sp.communicate() 

def authenticate(): 
    pwd = '' 
    for i in range(5): 
     sp = subprocess.Popen(['sudo', '-S', '-v'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
     sp.communicate(pwd + '\n') 
     if sp.returncode == 0: 
      return True 
     if i == 0: 
      print "Please enter user password." 
     else: 
      print "Incorrect password. Please try again." 
     pwd = getpass.getpass() 
    return False 
相關問題