首页 > 解决方案 > 我正在尝试使用 bash 脚本检查输入的系统密码是否正确,使用 subprocess()

问题描述

我正在制作一个用户输入系统密码并检查它的程序。

我正在使用subprocess()将密码传递给 bash 中的随机安装命令,并尝试使用 check_output 获取抓取输出,并根据某个值进行检查,但无法这样做。

这是我尝试过的

import os

import subprocess

def mainFunction(password):

    commandToRunRouter="echo " +password + " | sudo -S  install  something"
    answer=subprocess.check_output(commandToRunRouter,shell=True)
    print("result")
    print(answer)
    if answer!=0:
        return False
    return True

答案变量应该存储'Sorry wrong password.'输入错误密码时显示的值,但它存储了一些随机变量。

我究竟做错了什么??

标签: python-3.xbash

解决方案


查看以下文档check_output

如果返回码不为零,则会引发 CalledProcessError。CalledProcessError 对象将在 returncode 属性中具有返回码,在输出属性中具有任何输出。

这意味着您必须捕获异常并从那里读出输出。还要确保捕获stdoutstderr. 这样的事情可能对你有用:

import os

import subprocess

def mainFunction(password):

    commandToRunRouter="echo " +password + " | sudo -S  install  something"
    try:
        answer=subprocess.check_output(commandToRunRouter,shell=True, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as cpe:
        print(cpe.returncode)
        print(cpe.output)
        return False
    return True

还要考虑不要通过管道传递密码,因为这可能是一个安全问题。


推荐阅读