python-3.x - 我正在尝试使用 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.'
输入错误密码时显示的值,但它存储了一些随机变量。
我究竟做错了什么??
解决方案
查看以下文档check_output
:
如果返回码不为零,则会引发 CalledProcessError。CalledProcessError 对象将在 returncode 属性中具有返回码,在输出属性中具有任何输出。
这意味着您必须捕获异常并从那里读出输出。还要确保捕获stdout
和stderr
. 这样的事情可能对你有用:
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
还要考虑不要通过管道传递密码,因为这可能是一个安全问题。
推荐阅读
- java - 在 2.23.0 版本中,如果没有 CamelContext,则无法创建 Camel DefaultMessage
- javascript - 如何检查字符串是否包含多个单词?
- wso2 - 将存储在 Iterator 中的属性添加为 Iterator 外部的兄弟姐妹
- node.js - 未安装 React-trello 以响应 JS 项目
- django - 跨越多个关系的 Django 数据库查询
- php - 当值为负时,laravel sum 集合忽略
- flutter - Flutter安装问题,如何解决这个问题?
- ios - Apple 帐户中缺少 NSFileProtectionNone
- excel - 在网络驱动器上共享 *.xlam - 调用 subs 和函数
- php - Lumen whereRaw 与 Prepared Statement 不返回任何内容