我如何使用sudo执行bash的功能? [英] How can I execute a bash function using sudo?

查看:165
本文介绍了我如何使用sudo执行bash的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过导出函数,然后使用bash执行它,但是,这并不工作:​​

  $出口-f my_func,并将
$ sudo的庆典-c'my_func,并将
庆典:my_func,并将:命令未找到

如果我尝试运行使用bash的功能没有sudo(bash的-c'my_func,并将'),它的工作原理。

任何想法?


解决方案

bmargulies 答案开始,我写了一个函数来弥补这一问题,基本上实现了自己的想法。

 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#EXESUDO
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~#

#用途:
#------------------------------------------------- -------------------#
#执行使用sudo功能

#PARAMS:
#------------------------------------------------- -------------------#
#$ 1:字符串:函数的名称,使用sudo执行

#用途:
#------------------------------------------------- -------------------#
#exesudofuncname的后面的任何参数

#------------------------------------------------- -------------------#
#创建2012年9月1日最后修改02 2012年9月功能exesudo()
{
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ##
    #
    #局部变量:
    #
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ##    #
    #我使用下划线记住它已经过去了
    当地_funcname _ =$ 1    当地PARAMS =($ @)##包含所有PARAMS这里传递的数组
    当地TMPFILE =的/ dev / shm的/ $ RANDOM##的临时文件
    临时文件的本地filecontent ##内容
    当地正则表达式##定期EX pression
    当地FUNC功能##来源
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ##
    #
    #主code:
    #
    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~ ##    #
    #工作PARAMS:
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~    #
    #移位所述第一参数(这是函数名)
    未设置PARAMS [0] ##取出第一个元素
    #PARAMS =($ {PARAMS [@]})##重新包装阵列
    #
    #工作的临时文件:
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~    内容=#!/斌/ bash的\\ n \\ n    #
    #写参数数组
    内容=$ {}内容PARAMS =(\\ N    正则表达式=\\ S +
    在参数$ {PARAMS [@]}
    做
        如果[$参数=〜$正则表达式]
            然后
                内容=$ {}内容\\ t \\$ {参数} \\\\ n
            其他
                内容=$ {}内容\\ T $ {参数} \\ n
        科幻
    DONE    内容=$内容)\\ n
    回声-e$内容> $ TMPFILE    #
    #附加功能源
    回声#$(类型为$ ​​_funcname_)>> $ TMPFILE    #
    #追加调用函数
    回声-e\\ n _funcname_ $ \\\\ $ {PARAMS [@]} \\\\ n>> $ TMPFILE
    #
    #DONE:执行临时文件使用sudo
    #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
    sudo的庆典$ TMPFILE
    RM$ TMPFILE
}

搜索结果
用法示例:
结果运行下面的代码片段

 #!/斌/庆典功能exesudo()
{
    #在这里复制previous exesudo功能!
}test_it_out()
{
    当地PARAMS =($ @)
    回声你好$(WHOAMI)!
    回声你通过了以下params:一个
    printf的%S \\ n$ {PARAMS [@]}##打印阵列
}回声1.调用没有sudo
test_it_out第一第二回声
回声2.使用sudo调用
exesudo test_it_out -n约翰·多恩-s完成出口

搜索结果
将输出


  

      
  1. 调用没有sudo结果
      您好提供yourname!结果
      你通过了以下params:一个结果
      第一个结果
      第二个结果


  2.   
  3. 使用sudo结果调用
      您好根!结果
      你通过了以下params:一个结果
      -n结果
      约翰·多恩结果
      -s结果
      富结果


  4.   

搜索结果
如果你需要使用这个在shell调用这是在您的.bashrc中定义的函数,要求对<一个类似的问题href=\"http://serverfault.com/questions/177699/how-can-i-execute-a-bash-function-with-sudo/423546#423546\">serverfault由其他用户,那么你必须把previous exesudo功能上相同的的.bashrc 文件,以及像如下:

 函数yourfunc()
{
回声你好$(WHOAMI)!
}
出口-f yourfunc功能exesudo()
{
   #复制到这里
}
出口-f exesudo

搜索结果
然后,你必须注销并重新登录或使用

 源的〜/ .bashrc

搜索结果
最后,你可以使用exesudo如下:

  $ yourfunc
您好提供yourname!$ exesudo yourfunc
您好根!

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

$ 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.

Any idea?

解决方案

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

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
# EXESUDO
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
#
# Purpose:
# -------------------------------------------------------------------- #
# Execute a function with sudo
#
# Params:
# -------------------------------------------------------------------- #
# $1:   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_="$1"

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


    ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
    #
    # 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



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 serverfault by another user, then you have to put the previous exesudo function on the same bashrc file as well, like the following:

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:

$ yourfunc
Hello yourname!

$ exesudo yourfunc
Hello root!

这篇关于我如何使用sudo执行bash的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆