简体   繁体   English

如何通过 Python 程序以该用户身份切换用户并执行多个终端命令

[英]How can I switch user and perform multiple terminal commands as that user through a Python program

I am working on an automation program that I want able to run this string of Linux commands in succession, then close the subprocess: "su my_user", "cd ~/asdf/qwer/", and "sudo bash zxcv_zcv.sh".我正在开发一个自动化程序,我希望能够连续运行这串 Linux 命令,然后关闭子进程:“su my_user”、“cd ~/asdf/qwer/”和“sudo bash zxcv_zcv.sh”。

I am on python 2.7 and I have tried using these commands so far:我在 python 2.7 上,到目前为止我已经尝试使用这些命令:

subprocess.call("su my_user; cd ~/asdf/qwer/; sudo bash zxcv_zcv.sh",shell=True)
subprocess.Popen("su my_user; cd ~/asdf/qwer/; sudo bash zxcv_zcv.sh",shell=True)
os.system("su my_user; cd ~/asdf/qwer/; sudo bash zxcv_zcv.sh")

so far, the only thing that happens is the program creates a new terminal that I can interact with under my_user.到目前为止,唯一发生的事情是程序创建了一个新终端,我可以在 my_user 下与之交互。 I do not want to even see the terminal and this has not happened for any other Linux command I have run through subprocess or os.我什至不想看到终端,这对于我通过子进程或操作系统运行的任何其他 Linux 命令都没有发生。 Does anyone know what is happening and how I can fix this?有谁知道发生了什么以及我该如何解决这个问题?

Okay, I just found the answer to this question for anyone wondering.好的,我刚刚为任何想知道的人找到了这个问题的答案。 For the string of commands I used, just add a -c between "su" and "my_user" and it will run fine.对于我使用的命令字符串,只需在“su”和“my_user”之间添加 -c 即可运行良好。

subprocess.call("su -c my_user; cd ~/asdf/qwer/; sudo bash zxcv_zcv.sh", shell=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过 Windows 中的终端在 python 中请求用户输入? - How can I ask for user input in python through the terminal in windows? 如何在终端MAC中通过python执行命令? - How can I execute commands through python in terminal MAC? 如何允许用户根据用户输入在程序中存储多个 CSV 文件? - Python - How can I allow the user to store multiple CSV files in a program from user input? - Python 使用 python 在用户终端中输入命令 - Typewritting commands in user's terminal using python 在 python 中运行终端命令后,如何将用户输入终端? - How can I give a user input into terminal after running a terminal command in python? 当我使用 subprocess.call() 切换用户时,如何保持程序运行? - How can I keep my program running when I use subprocess.call() to switch user? 如何打开 linux 终端并通过 python 传递命令 - How can I open linux terminal and pass it commands via python 如何通过 Windows 上的 Python 子进程一次运行多个 shell 命令? - How can I run multiple shell commands at once through a Python subprocess on Windows? 如何在同一终端中通过Python在CMD中执行多个任务而不关闭窗口 - How to perform multiple tasks in CMD through Python in the same terminal and without the window closing Python和子进程-以用户身份打开终端会话并执行一个/两个命令 - Python & subprocess - Open terminal session as user and execute one/two commands
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM