Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Disclaimer: I'm pretty novice at sysadmin stuff.

I'm trying to set up port forwarding in an AWS EC2 instance, this has to be done in the command-line because I don't want to go in and edit anything, it has to be automatic (it's part of a build process).

sudo echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf

Permission denied

The weird thing is I've been (successfully) using sudo for pretty much every command that required su privileges. If I do sudo su before the command (trying it out by hand in an ssh session), then it works.

Reasons behind this? Possible solutions that don't involve sudo su or manual edits?

share|improve this question
    
Same problem here:stackoverflow.com/questions/82256/… -- Also, if you want to be really risky: sudo -i –  MirroredFate Sep 20 '13 at 19:22

4 Answers 4

up vote 19 down vote accepted

You can't use sudo to affect output redirection; > and >> are effected with the privilege of the calling user, because redirection is done by the calling shell, not the called subprocess.

Either do

cp /etc/sysctl.conf /tmp/
echo "net.ipv4.ip_forward = 1" >> /tmp/sysctl.conf
sudo cp /tmp/sysctl.conf /etc/

or

sudo /bin/su -c "echo 'net.ipv4.ip_forward = 1' >> /etc/sysctl.conf"
share|improve this answer
1  
This makes a lot of sense, thanks for the explanation! –  Nico Sep 20 '13 at 14:22

You might find it simpler to use this command:

echo net.ipv4.ip_forward = 1 | sudo tee -a /etc/sysctl.conf
share|improve this answer

The command sudo echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf is interpreted as that you (nonroot) write the result of sudo echo "net.ipv4.ip_forward = 1" into /etc/sysctl.conf.

Run

sudo -s 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'

or

sudo su -c 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'

to run echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf as root.

share|improve this answer

sudo runs only your command, not the redirect, as root. You'll need to wrap it all in a command where the whole thing runs as root:

sudo sh -c 'echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.