gpt4 book ai didi

python - Popen 命令链接返回 0 而不是 1

转载 作者:太空狗 更新时间:2023-10-29 12:01:19 26 4
gpt4 key购买 nike

所以我是 Python 的新手。我正在做一个登录表单,将您重定向到在 linux 服务器上运行的 python 脚本以对用户进行身份验证。我一次使用多个命令来查看用户是否在数据库中。命令是 echo "$password"| login -p -h 192.0.. $user >/dev/null 2>&1当我回应 $?如果它在数据库中,它应该返回 0,否则应该返回 1。

在 python 脚本中我有这个:

import cgi,shlex,subprocess

form = cgi.FieldStorage()

params={}

for key in form.keys():
params[key]= form[key].value

user_name_variable=params['id']
password_variable=params['pwd']

command1="login -p -h 192.0. "+user_name_variable+" >/dev/null 2>&1"
command2="echo "+password_variable
command3="'echo $?'"
p1=subprocess.Popen(shlex.split(command2),shell=True,stdout=subprocess.PIPE)
p2=subprocess.Popen(shlex.split(command1),shell=True,stdin=p1.stdout, stdout=subprocess.PIPE)
p3=subprocess.Popen(shlex.split(command3),shell=True, stdin=p2.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
p2.stdout.close()
out, err= p3.communicate()[0]

即使输入错误,out 也始终为 0。我用 PIPE 做的有什么问题吗?我所知道的是,问题不在于我传递变量时,因为我得到了正确的变量。问题一定出在链接中。我将不胜感激你的帮助。谢谢。

最佳答案

$? 是一个 shell 变量,它在这里没有意义(每个子进程都在其自己的子 shell 中运行 shell=True$ ? from login 仅在其 shell 中可见,而不是您尝试在 echo $? 中显示的那个)。

但是 Popen 对象已经提供了它们的退出状态,因此您根本不需要运行任何东西。您还尝试使用 shlex.split 非法拆分带有 shell 元素的命令(您要么传递单个字符串和 shell=True,要么传递一系列参数 shell=False;混合使用是非法的)。您也可以在这里削减很多进程,并避免运行在命令行中包含密码的命令:

# Define command as a list directly; making a string and splitting it is silly
command1 = ['login', '-p', '-h', '192.0.', user_name_variable]

# Only need a single Popen; we can pass it stdin and read its status directly
# As the shell command did, we throw away stdout and keep stderr
p1=subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)


# Sends the password, closes proc stdin, waits for proc to complete slurping
# the stderr (stdout was thrown away so it's returned empty)
_, err = p1.communicate(password_variable)

# Process is complete, so we can just ask for the return code
if p1.returncode != 0:
... handle failed run ...

备注:subprocess.DEVNULL是 3.3 中的新内容;如果您使用的是较旧的 Python,请替换为:

with open('/dev/null', 'wb') as devnull:
p1 = subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=devnull, stderr=subprocess.PIPE)

或者只是将其更改为 subprocess.PIPE 并忽略捕获的标准输出输出。

关于python - Popen 命令链接返回 0 而不是 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35073166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com