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

时间:2016-10-10 08:22:18

标签: 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

有任何帮助吗?感谢

1 个答案:

答案 0 :(得分:0)

您可以使用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