简体   繁体   English

如何在python脚本中使用带有密码命令的“ sudo”?

[英]How to use a “sudo” with password command in a python script?

I need to run a sudo command in my script to turn on and off network connections for an script I'm doing. 我需要在脚本中运行sudo命令以打开和关闭我正在执行的脚本的网络连接。 The password is plain text in the code for this example, but it will be in a jumbled for in a hidden file for the real program. 在此示例中,密码是纯文本形式的密码,但是对于真实程序,该密码将被隐藏在一个隐藏文件中。

I tried multiple online examples of code, including popen and call,and nothing worked, but they didnt work and I dont really understand how they work. 我尝试了多个在线代码示例,包括popen和call,但没有任何效果,但是它们没有效果,我也不十分了解它们的工作原理。

def run_script(script, stdin=None):
    proc = subprocess.Popen(['sudo' , 'bash', '-c', script],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        stdin=subprocess.PIPE)
    proc.communicate(b'password')
command = "ip link set enp6s0 down"
run_script(command)

The script runs, but it wont actually do anything. 该脚本可以运行,但实际上不会执行任何操作。 No error. 没错

sudo有一个名为“ -S”的参数,下面有帮助:

sudo bash -c 'your script' -S your_password

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

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