如何使用 sudo 将输出重定向到我无权写入的位置? [英] How do I use sudo to redirect output to a location I don't have permission to write to?
问题描述
我获得了对我们开发的 RedHat linux 机器之一的 sudo 访问权限,而且我似乎发现自己经常需要将输出重定向到我通常没有写访问权限的位置.
I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.
问题是,这个人为的例子不起作用:
The trouble is, this contrived example doesn't work:
sudo ls -hal /root/ > /root/test.out
我刚刚收到回复:
-bash: /root/test.out: Permission denied
我怎样才能让它发挥作用?
How can I get this to work?
推荐答案
你的命令不起作用,因为重定向是由你的 shell 执行的,它没有写入 /root/test.out 的权限代码>.输出的重定向不是由 sudo 执行的.
Your command does not work because the redirection is performed by your shell which does not have the permission to write to /root/test.out
. The redirection of the output is not performed by sudo.
有多种解决方案:
使用 sudo 运行一个 shell 并使用
-c
选项给它命令:
sudo sh -c 'ls -hal /root/ > /root/test.out'
使用您的命令创建一个脚本并使用 sudo 运行该脚本:
Create a script with your commands and run that script with sudo:
#!/bin/sh
ls -hal /root/ > /root/test.out
运行 sudo ls.sh
.如果您不想创建临时文件,请参阅 Steve Bennett 的答案.
Run sudo ls.sh
. See Steve Bennett's answer if you don't want to create a temporary file.
用 sudo -s
启动一个 shell,然后运行你的命令:
Launch a shell with sudo -s
then run your commands:
[nobody@so]$ sudo -s
[root@so]# ls -hal /root/ > /root/test.out
[root@so]# ^D
[nobody@so]$
使用 sudo tee
(如果你在使用 -c
选项时不得不转义很多):
Use sudo tee
(if you have to escape a lot when using the -c
option):
sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null
需要重定向到 /dev/null
来停止 tee 从输出到屏幕.append 而不是覆盖输出文件(>>
),使用 tee -a
或 tee --append
(最后一个是特定于 GNU coreutils).
The redirect to /dev/null
is needed to stop tee from outputting to the screen. To append instead of overwriting the output file
(>>
), use tee -a
or tee --append
(the last one is specific to GNU coreutils).
感谢Jd,Adam J. Forster 和 Johnathan 用于第二、第三和第四个解决方案.
Thanks go to Jd, Adam J. Forster and Johnathan for the second, third and fourth solutions.
这篇关于如何使用 sudo 将输出重定向到我无权写入的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!