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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:03:09  来源:igfitidea点击:

bash run function with different user

bashsudo

提问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. sudolets 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 RunStefanocommand; 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/whoamito backticks:

顺便说一句,您还需要将周围的撇号/usr/bin/whoami改为反引号:

echo "Ciao, `/usr/bin/whoami`"

And you should read the documentation for the sudocommand; it doesn't have a -coption.

您应该阅读该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