我已经在我们开发的一个RedHat linux机器上获得了sudo访问权,我似乎发现自己经常需要将输出重定向到一个我通常没有写访问权的位置。

问题是,这个人为的例子不起作用:

sudo ls -hal /root/ > /root/test.out

我刚刚收到回复:

-bash: /root/test.out: Permission denied

我怎样才能让它工作呢?


当前回答

让sudo运行一个shell,像这样:

sudo sh -c "echo foo > ~root/out"

其他回答

问题是命令在sudo下运行,而重定向在您的用户下运行。这是由shell完成的,对此您几乎无能为力。

sudo command > /some/file.log
`-----v-----'`-------v-------'
   command       redirection

通常绕过这个的方法是:

Wrap the commands in a script which you call under sudo. If the commands and/or log file changes, you can make the script take these as arguments. For example: sudo log_script command /log/file.txt Call a shell and pass the command line as a parameter with -c This is especially useful for one off compound commands. For example: sudo bash -c "{ command1 arg; command2 arg; } > /log/file.txt" Arrange a pipe/subshell with required rights (i.e. sudo) # Read and append to a file cat ./'file1.txt' | sudo tee -a '/log/file.txt' > '/dev/null'; # Store both stdout and stderr streams in a file { command1 arg; command2 arg; } |& sudo tee -a '/log/file.txt' > '/dev/null';

写一个脚本怎么样?

Filename: myscript

#!/bin/sh

/bin/ls -lah /root > /root/test.out

# end script

然后使用sudo运行脚本:

sudo ./myscript

刚才有人建议sudo tee:

sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null

这也可以用于将任何命令重定向到您没有访问权限的目录。它之所以有效,是因为tee程序实际上是一个“回显到文件”程序,重定向到/dev/null是为了阻止它也输出到屏幕,以保持它与上面最初的人为示例相同。

这是基于tee的答案。为了让事情更简单,我写了一个小脚本(我叫它suwrite),并把它放在/usr/local/bin/ +x权限:

#! /bin/sh
if [ $# = 0 ] ; then
    echo "USAGE: <command writing to stdout> | suwrite [-a] <output file 1> ..." >&2
    exit 1
fi
for arg in "$@" ; do
    if [ ${arg#/dev/} != ${arg} ] ; then
        echo "Found dangerous argument ‘$arg’. Will exit."
        exit 2
    fi
done
sudo tee "$@" > /dev/null

如代码中的USAGE所示,您所要做的就是将输出输出输送到这个脚本,后面跟着所需的超级用户可访问的文件名,如果需要的话,它将自动提示您输入密码(因为它包含sudo)。

echo test | suwrite /root/test.txt

注意,由于这是tee的一个简单包装器,它也将接受tee的-a选项来追加,并且还支持同时写入多个文件。

echo test2 | suwrite -a /root/test.txt
echo test-multi | suwrite /root/test-a.txt /root/test-b.txt

它也有一些简单的保护,防止写入/dev/设备,这是该页的一个评论中提到的一个问题。

也许你只被授予sudo访问一些程序/路径?那就没办法做你想做的事了。(除非你能破解)

如果不是这样,那么也许你可以编写bash脚本:

cat > myscript.sh
#!/bin/sh
ls -hal /root/ > /root/test.out 

按ctrl + d:

chmod a+x myscript.sh
sudo myscript.sh

希望能有所帮助。