Python中的sudo pass自动密码

2024-04-27 04:14:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

然后我试着用pexpect

^{pr2}$

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


Tags: 文件脚本权限permissions密码进程shstdin
2条回答
# 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())

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

相关问题 更多 >