[英]how to use sudo su - username in python script and pass password to it
I got frustrated, after searching in all available forums for this answer.. I want to use sudo su - username
inside a python script and also I need to assign password as well to it in script itself.在所有可用论坛中搜索此答案后,我感到沮丧.. 我想在 python 脚本中使用sudo su - username
并且我还需要在脚本本身中为其分配密码。
sudo su - username
Please let me know if this is possible or not.请让我知道这是否可能。
Thanks谢谢
You can simply use subprocess in the following way:您可以通过以下方式简单地使用子流程:
sudoPassword = "your sudo password"
command = "your command"
commandFinal = "echo " + sudoPassword + " | sudo -S " + command
output = subprocess.Popen(commandFinal, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = (output.communicate())
out = (out[0].strip())
Please don't be frustrated we are here to help you.请不要沮丧,我们在这里为您提供帮助。 Use below command in your python script:-在您的 python 脚本中使用以下命令:-
sudo -u USER -S password
Suppose you are executing a second script as sudo
:-假设您正在以sudo
身份执行第二个脚本:-
echo $password | sudo -u USER -S ./yourscript.sh
In python script use like below:-在 python 脚本中使用如下:-
command = 'yourcommand'
os.system('echo %s|sudo -u %s -S %s' % (sudoPassword, user, command))
Also simply use like below without user也只需在没有用户的情况下使用如下所示
os.system('echo %s|sudo -S %s' % (sudoPassword, command))
os.system('echo %s|sudo -S ' % (sudoPassword))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.