以root身份运行shell命令并使用python检测失败的密码尝试

时间:2013-12-17 16:29:16

标签: python shell

我有一个我写的python函数,它可以使用子进程以root身份运行shell命令。我正在尝试添加功能来检测错误的密码尝试。这是功能。

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()

1 个答案:

答案 0 :(得分: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