我正在尝试在 python 脚本中使用 su
linux 命令以及 getpass
和 subprocess
python 标准库来切换到新用户在执行我的脚本之前。我正在使用这个功能:
import subprocess
import getpass
def ask_passwd():
pw = getpass.getpass(prompt='Please insert the passwd to use the auto api:') # prompt the user for a passwd
print pw
command = "su new_user"
p = subprocess.Popen(command.split(), stdin=subprocess.PIPE)
p.communicate(pw) # communicate the passwd
def main():
# code here
if __name__ == '__main__':
ask_passwd()
main()
执行脚本时,主要代码有效,但 su
命令无效。这是我得到的结果:
Please insert the passwd to use the auto api:
pass
su: must be run from a terminal
有什么帮助吗?谢谢
最佳答案
你可以使用 subprocess.popen。有个例子
import subprocess
sudo_password = 'yourpassword'
command = '-i -u youruser \n id'
command = command.split()
cmd1 = subprocess.Popen(['echo', sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo', '-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)
output = cmd2.stdout.read()
print output
关于python - 在执行 python 脚本之前切换用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39954066/