如何以其他用户身份登录,然后在 bash 脚本中注销?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2538624/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to login as another user and then log out in bash script?
提问by Neuquino
I need to write a bash script to do something as another user and then return to the initial user...
我需要编写一个 bash 脚本来作为另一个用户做一些事情,然后返回到初始用户......
Suppose I run the following as root:
假设我以 root 身份运行以下命令:
#!/bin/bash
USER=zaraza
su - "${USER}"
#do some stuff as zaraza
________ #here I should logout zaraza
#continue doing things as root
In the console I should write "exit", but in bash is a keyword and it exits the script...
在控制台中我应该写“退出”,但在 bash 中是一个关键字,它退出脚本......
Thanks in advance,
提前致谢,
回答by
Use su -c. From the man page:
使用su -c. 从手册页:
su man -c catman Runs the command catman as user man. You will be asked for man's password unless your real UID is 0.
su man -c catman Runs the command catman as user man. You will be asked for man's password unless your real UID is 0.
回答by Paul Tomblin
The simplest way is to make the stuff that has to run as the other user a separate script and invoke it with the "-c" option in su, like su -c otherscript userid.
最简单的方法是将必须作为其他用户运行的内容作为单独的脚本,并使用 su 中的“-c”选项调用它,例如su -c otherscript userid.
You may be able to do that as a "here script" with << EOF, but I've never tried it.
您可以使用 将其作为“此处脚本”来执行<< EOF,但我从未尝试过。
回答by mdm
You could also use sudo.
您也可以使用sudo.
回答by kSiR
This will do it.
这将做到。
su - ${username} -c /path/to/the/shellscript.sh
su - ${username} -c /path/to/the/shellscript.sh

