关于sudo的一些问题

2246阅读 0评论2007-09-27 linux_arm
分类:LINUX

今天在研究dsniff的时候,需要打开ip转发,执行命令如下:
 sudo echo 1> /proc/sys/net/ipv4/ip_forward

本意以为一切顺利,但是却出现这样的提示:
bash: /proc/sys/net/ipv4/ip_forward: Permission denied

百思不得其解,在Google大哥的帮助下找到了如下文章:

(来自:)

======================================================================

May 17th 2006 Posted to ,

The other day I wanted to enable IP forwarding on my Linux box (so that it could forward packets from a tun virtual interface being used by to the physical interface connected to my home network).

I looked up it up and it turns out that it’s a simple setting in a file in the /proc filesystem, so I did what seemed obvious and logical at the time:

marca:~$ sudo echo "1" > /proc/sys/net/ipv4/ip_forward
-bash: /proc/sys/net/ipv4/ip_forward: Permission denied

I took this to mean that my kernel was not compiled with ip_forward support and then wasted a bunch of time building a new kernel.

Finally, it dawned on me. Duh. The echo command is a shell built-in so sudo has no effect.

I didn’t need a new kernel. All I had to do was:

marc:~$ sudo bash
root:~# sudo echo "1" > /proc/sys/net/ipv4/ip_forward
root:~# cat /proc/sys/net/ipv4/ip_forward
1

or even:

marc:~$ sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'

Sigh.

I thought of the idea of preventing this in the future by defining a bash function that detects builtins:

function sudo()
{
if [ $(type -t "$1") == "builtin" ]; then
echo "sudo bash function: ERROR - \"$1\" is a shell builtin" 1>&2
return 1
fi

command sudo "$@"
}

which works for some cases but unfortunately doesn’t help for the case above, because the redirection permissions are checked before the function is executed. Sigh.


=============================================================================================
大概意思是说echo是一个shell-builtin的命令,所以sudo不起作用,因此可以换做如下任一命令:
$ sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'


$ sudo bash
# sudo echo "1" > /proc/sys/net/ipv4/ip_forward

我经过试验是可以成功的,但是还是有些疑惑,为什么shell-builtin就不起作用了呢?sudo它本质上是个什么机制?
渴望各位的解答:-)


上一篇:一个数学编程题目
下一篇:计算机中的原码、反码和补码及偏移2进制码