sudo 在 Python 中传递自动密码

sudo pass automatic password in Python

我想从 python 脚本调用 .sh 文件。这需要 sudo 权限,我想在没有提示的情况下自动传递密码。我尝试使用子进程。

(VAR1 是我要传递的变量,permissions.sh 是我要从 python 脚本调用的 sh 文件)

process = subprocess.Popen(['sudo', './permissions.sh', VAR1], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
process.communicate(password)

然后我尝试使用 pexpect

child = pexpect.spawn('sudo ./permissions.sh'+VAR1)
child.sendline(password)

在这两种情况下,它仍然会在终端上提示输入密码。我想自动传递密码。我不想使用 os 模块。如何做到这一点?

会使用 pexpect,但你需要告诉它在 sudo 之后会发生什么:

#import the pexpect module
import pexpect
# here you issue the command with "sudo"
child = pexpect.spawn('sudo /usr/sbin/lsof')
# it will prompt something like: "[sudo] password for < generic_user >:"
# you "expect" to receive a string containing keyword "password"
child.expect('password')
# if it's found, send the password
child.sendline('S3crEt.P4Ss')
# read the output
print(child.read())
# the end
# use python3 for pexpect module e.g python3 myscript.py
import pexpect
# command with "sudo"
child = pexpect.spawn('sudo rm -f')
# it will prompt a line like "abhi@192.168.0.61's password:"
# as the word 'password' appears in the line pass it as argument to expect
child.expect('password')
# enter the password
child.sendline('mypassword')
# must be there
child.interact()
# output
print(child.read())