简体   繁体   English

如何使用 sudo 命令在 python 中工作

[英]How do I use a sudo command to work in python

I am using ubuntu and I am trying to check if the password field is empty.我正在使用 ubuntu 并尝试检查密码字段是否为空。

import subprocess

pass_max = subprocess.check_output({'"sudo'", "cat",  "/etc/shadow", "|", "awk", "{print}"])

After executing this code, i receive the error returned non-zero exit status 1. How do I resolve this issue?执行此代码后,我收到错误返回非零退出状态 1。如何解决此问题? Is the error because of the sudo command?错误是因为 sudo 命令吗?

Have you tried shlex?你试过shlex吗?

import subprocess
import shlex

pass_max = subprocess.check_output(shlex.split("sudo cat /etc/shadow | awk '{print}'"))

I think the problem is not sudo but pipe operator |我认为问题不是sudo而是 pipe 运算符| in the argument of check_output.在 check_output 的参数中。

At least in my environment, the following works.至少在我的环境中,以下工作。

import subprocess as sp


with sp.Popen(["sudo", "cat", "6.py"], stdout=sp.PIPE) as p1:
    with sp.Popen(["grep", "with"], stdin=p1.stdout, stdout=sp.PIPE) as p2:
        print(p2.stdout.read().decode("utf-8"))
print(p1.returncode)
print(p2.returncode)

output was output 是

$ python 6.py
Password:
with sp.Popen([sudo, cat, 6.py], stdout=sp.PIPE) as p1:
    with sp.Popen([grep, with], stdin=p1.stdout, stdout=sp.PIPE) as p2:

0
0

(I saved my code as 6.py) (我将代码保存为 6.py)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM