sudo在Python中传递自动密码

时间:2018-02-06 09:29:52

标签: python subprocess sudo spawn pexpect

我想从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模块。怎么办呢?

2 个答案:

答案 0 :(得分:1)

会使用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

答案 1 :(得分:0)

# 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())