如何使用 sudo 执行 bash 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9448920/
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 01:39:19  来源:igfitidea点击:

How can I execute a bash function using sudo?

bashfunctionsudo

提问by Miroslav

I tried exporting the function and then executing it with bash, but that doesn't work:

我尝试导出该函数,然后使用 bash 执行它,但这不起作用:

$ export -f my_func
$ sudo bash -c 'my_func' 
bash: my_func: command not found

If I try to run the function with bash without sudo (bash -c 'my_func'), it works.

如果我尝试在没有 sudo 的情况下使用 bash 运行该函数(bash -c 'my_func'),它会起作用。

Any idea?

任何的想法?

采纳答案by Luca Borrione

Starting from the answer of bmargulies, I wrote a function to cover this issue, which basically realizes his idea.

bmargulies的回答开始,我写了一个函数来覆盖这个问题,基本实现了他的想法。

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# EXESUDO
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
#
# Purpose:
# -------------------------------------------------------------------- #
# Execute a function with sudo
#
# Params:
# -------------------------------------------------------------------- #
# :   string: name of the function to be executed with sudo
#
# Usage:
# -------------------------------------------------------------------- #
# exesudo "funcname" followed by any param
#
# -------------------------------------------------------------------- #
# Created 01 September 2012              Last Modified 02 September 2012

function exesudo ()
{
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
    #
    # LOCAL VARIABLES:
    #
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

    #
    # I use underscores to remember it's been passed
    local _funcname_=""

    local params=( "$@" )               ## array containing all params passed here
    local tmpfile="/dev/shm/$RANDOM"    ## temporary file
    local content                       ## content of the temporary file
    local regex                         ## regular expression


    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
    #
    # MAIN CODE:
    #
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##

    #
    # WORKING ON PARAMS:
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    #
    # Shift the first param (which is the name of the function)
    unset params[0]              ## remove first element
    # params=( "${params[@]}" )     ## repack array


    #
    # WORKING ON THE TEMPORARY FILE:
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    content="#!/bin/bash\n\n"

    #
    # Write the params array
    content="${content}params=(\n"

    regex="\s+"
    for param in "${params[@]}"
    do
        if [[ "$param" =~ $regex ]]
            then
                content="${content}\t\"${param}\"\n"
            else
                content="${content}\t${param}\n"
        fi
    done

    content="$content)\n"
    echo -e "$content" > "$tmpfile"

    #
    # Append the function source
    echo "#$( type "$_funcname_" )" >> "$tmpfile"

    #
    # Append the call to the function
    echo -e "\n$_funcname_ \"${params[@]}\"\n" >> "$tmpfile"


    #
    # DONE: EXECUTE THE TEMPORARY FILE WITH SUDO
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    sudo bash "$tmpfile"
    rm "$tmpfile"
}



Example of usage:
running the following snippet



使用示例:
运行以下代码段

#!/bin/bash

function exesudo ()
{
    # copy here the previous exesudo function !!!
}

test_it_out ()
{
    local params=( "$@" )
    echo "Hello "$( whoami )"!"
    echo "You passed the following params:"
    printf "%s\n" "${params[@]}" ## print array
}

echo "1. calling without sudo"
test_it_out "first" "second"

echo ""
echo "2. calling with sudo"
exesudo test_it_out -n "john done" -s "done"

exit



Will output



会输出

  1. calling without sudo
    Hello yourname!
    You passed the following params:
    first
    second

  2. calling with sudo
    Hello root!
    You passed the following params:
    -n
    john done
    -s
    foo

  1. 没有 sudo 的
    呼叫 你好你的名字!
    您传递了以下参数:
    第一

  2. 用 sudo
    呼叫 你好 root!
    您传递了以下参数:
    -n
    john done
    -s
    foo



If you need to use this in a shell calling a function which is defined in your bashrc, as asked with a similar question on serverfaultby another user, then you have to put the previous exesudo function on the same bashrcfile as well, like the following:



如果您需要在调用 bashrc 中定义的函数的 shell 中使用它,正如另一个用户在serverfault上的类似问题所问的那样,那么您必须将之前的 exesudo 函数也放在同一个bashrc文件中,例如下列的:

function yourfunc ()
{
echo "Hello "$( whoami )"!"
}
export -f yourfunc

function exesudo ()
{
   # copy here
}
export -f exesudo



Then you have to logout and login again or use



然后您必须注销并重新登录或使用

source ~/.bashrc



Finally you can use exesudo as follow:



最后你可以使用 exesudo 如下:

$ yourfunc
Hello yourname!

$ exesudo yourfunc
Hello root!

回答by bmargulies

Each time you run sudo, it forks and execs a new copy of the shell, running as root. That shell does not inherit functions from your shell (it can't) and it doesn't inherit functions from previous executions. You will have to write out a file containing the function definition and invocation and sudo the invocation of that.

每次运行 sudo 时,它都会派生并执行一个新的 shell 副本,以 root 身份运行。该 shell 不会从您的 shell 继承函数(它不能),也不会从以前的执行中继承函数。您将不得不写出一个包含函数定义和调用的文件,并 sudo 调用它。

回答by Karatheodory

You can do that using declare -f, as in the following example:

您可以使用 来做到这一点declare -f,如下例所示:

function myfunc() {
    whoami
    echo First parameter is 
}

myfunc foo
DECL=`declare -f myfunc`

sudo bash -c "$DECL; myfunc bar"

回答by timothyashaw

An alternative to calling your function with sudo is to just move the "sudo " calls inside your function. For example, I was wanting to set up a shortcut function in OS X for forwarding localhost to a particular port.

使用 sudo 调用函数的另一种方法是在函数中移动“sudo”调用。例如,我想在 OS X 中设置一个快捷功能,用于将 localhost 转发到特定端口。

function portforward() {
    echo "y" | sudo ipfw flush;
    sudo ipfw add 100 fwd 127.0.0.1, tcp from any to any 80 in;
    echo "Forwarding localhost to port !";
}

The function hits sudo and asks for my password. (Then pipes "y" to a prompt for ipfw, not related to this question). After that, sudo is cached so the rest of the function executes without the need to enter a password.

该函数点击 sudo 并询问我的密码。(然后将“y”传递给 ipfw 的提示,与此问题无关)。之后, sudo 被缓存,因此函数的其余部分无需输入密码即可执行。

Essentially, this just runs like:

本质上,这只是运行如下:

portforward 8000
Password:
Forwarding localhost to port 8000!

And fills my need because I only need to enter the password once and it's taken care of. Although it's a little ugly if you fail to enter the password the first time. Extra points for detecting whether the first sudo succeeded and exiting the function if not.

并满足我的需要,因为我只需要输入一次密码就可以了。虽然第一次不输入密码有点难看。用于检测第一个 sudo 是否成功并退出函数的额外点。

回答by Shavais

For short and simple stuff that doesn't have single quotes in it, this works for me:

对于没有单引号的简短内容,这对我有用:

export code='
function whoAmI() {
    echo `whoami`
}

whoAmI
'
sudo bash -c "$code"

# output: root

回答by gospes

All you have to do is check if you are root, if yes, run the function, if not, call the script with sudo:

你所要做的就是检查你是否是 root,如果是,运行函数,如果不是,用 sudo 调用脚本:

#!/bin/bash
# script name: 'foo.sh'

function foo(){
    whoami
}

DIR=$( cd "$( dirname "##代码##" )" && pwd )   # get script dir
if [ "$UID" -ne 0 ]; then                # check if you are root
    sudo $DIR/foo.sh                     # NOT: run script with sudo
else
    foo                                  # YES: run function
fi

回答by Josh

If your function is in your .bashrc

如果你的函数在你的 .bashrc 中

Then just do sudo -i myfunc

然后就做 sudo -i myfunc