python - 在执行 python 脚本之前切换用户

标签 python linux

我正在尝试在 python 脚本中使用 su linux 命令以及 getpasssubprocess 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/

相关文章:

python - 从另一个 Azure Function 调用 Azure Function

python - 如何在python中将一个元素从列表移动到另一个元素

python - ValueError:无法将输入数组从形状(150528,1)广播到形状(150528)

c - C 中的 Fork() 程序

python - x86_64 执行 Shellcode 失败 :

linux - 在 HPC 上自动测试来自 SVN 的二进制文件

python - 使用 SQLAlchemy 进行动态 OR 过滤

具有多个参数的函数调用的 Python 编码风格

linux - linux删除文件中的特殊字符

linux - Poppler 0.14.1 构建问题