bash 不同用户的bash运行功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17926153/
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
bash run function with different user
提问by Stefano Radaelli
Would be possible to run a custom bash function with different priviledges?
可以运行具有不同权限的自定义 bash 函数吗?
#!/bin/bash
function RunStefano() {
while [ 1 ]; do
echo "Ciao, ′/usr/bin/whoami′"
sleep 10;
done &
}
export -f RunStefano;
echo "Welcome, ′/usr/bin/whoami′"
sudo -u stefano -c "RunStefano"
If I run this script with 'root' user, I want to receive as output:
如果我用“root”用户运行这个脚本,我想接收作为输出:
Welcome, root
Ciao, stefano
(...)
Ciao, stefano
Would it be possibile?
有可能吗?
采纳答案by Keith Thompson
You can't do that, at least not directly. (But see Richard Fletcher's answer.)
你不能这样做,至少不能直接这样做。(但请参阅理查德弗莱彻的回答。)
Each processruns under a particular user account. By default, that's the same account as the process that invoked it. sudo
lets a process running under one account launch another process that runs under a different account.
每个进程都在特定的用户帐户下运行。默认情况下,该帐户与调用它的进程相同。sudo
让在一个帐户下运行的进程启动在不同帐户下运行的另一个进程。
When you invoke a shell function, it doesn't launch a new process. With some modifications, your script should give you something like:
当您调用 shell 函数时,它不会启动新进程。通过一些修改,您的脚本应该为您提供以下内容:
sudo: RunStefano: command not found
In the new process created by sudo
, there is no RunStefano
command; the function is local to the process running the script.
新建的进程中sudo
,没有RunStefano
命令;该函数是运行脚本的进程的本地函数。
You need to isolate the function into a separate executable script; you can then invoke that script via sudo
.
您需要将函数隔离到一个单独的可执行脚本中;然后您可以通过调用该脚本sudo
。
Incidentally, you also need to change the apostrophes around /usr/bin/whoami
to backticks:
顺便说一句,您还需要将周围的撇号/usr/bin/whoami
改为反引号:
echo "Ciao, `/usr/bin/whoami`"
And you should read the documentation for the sudo
command; it doesn't have a -c
option.
您应该阅读该sudo
命令的文档;它没有-c
选择。
回答by Richard Fletcher
Yes, this is possible
是的,这是可能的
#!/bin/bash
function1(){
echo `whoami`
}
export -f function1
su username -c "bash -c function1"
exit 0