简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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