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

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

这很好用。我尝试添加以检测失败的密码尝试是解析标准错误,但我会在每个循环中得到不同的结果。请参阅下面的代码(我尝试将其添加到上面的函数中):

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

最佳答案

一个 friend 帮我想出了一个更好的解决方案来运行 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

关于python - 以 root 身份运行 shell 命令并使用 python 检测失败的密码尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20639534/

相关文章:

python - Pynotify 搞砸了日期时间,为什么?

linux - 从 Linux 命令行中,查找字符串出现的行数

bash - 哈希冒号 (# :) mean as first line of shell script?

sql - 使 postgreSQL 脚本可配置

php - Cron 不执行 shell 脚本..但从命令行工作

python - 如何找到我的 Pandas 数据框中的哪些列包含列表?

python - Python 中的定点迭代

python - getattr/setattr/hasattr/delattr 线程安全吗?

python - Bokeh:ColumnDataSource 未在 Vbar 上渲染

linux - 打印 file1 到 file2 的差异而不删除 file2 中的任何内容