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()
不應該sudo日誌已經這樣嗎? –