Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use sudo to change file in root directory [duplicate]

Tags:

bash

shell

I'm trying to write a script to configure resolv.conf and /etc/network/interfaces automatically. I'm running the commands as "sudo", but I'm getting "Permission denied" errors.

sudo apt-get --assume-yes install vsftpd
sudo "nameserver 8.8.8.8" >> /etc/resolv.conf
sudo python setinterfaces.py
sudo chattr +i /etc/network/interfaces
sudo apt-get --assume-yes install lamp-server^

Lines 2 and 3 get permission denied errors, but lines 1 and 5 did run. setinterfaces.py is supposed to overwrite /etc/network/interfaces'.setinterfaces.pyworks when pointed at the home folder but not theinterfaces` file.

Any idea? Do I have to be changing ownership? Ideally I'd like this to be a one command script, where I can just call it and it will run. I'm writing this script for people who are not experienced in *nix.

like image 257
Jacqlyn Avatar asked Dec 21 '25 04:12

Jacqlyn


1 Answers

The sudo command executes the command you give it under the root account. In its simplest form, the syntax is:

sudo command args...

For example:

sudo whoami

prints root.

If you type, as you did in your question:

sudo "nameserver 8.8.8.8" >> /etc/resolv.conf

then it's not going to work; it will try to execute a command named "nameserver 8.8.8.8", which doesn't exist. The problem there is that you're missing the echo command.

This:

sudo "echo nameserver 8.8.8.8" >> /etc/resolv.conf

still won't work because there's no command called "echo nameserver 8.8.8.8". That entire string is passed to sudo as a single argument. It needs to see the command and each of its arguments as a separate argument.

So this:

sudo echo nameserver 8.8.8.8 >> /etc/resolv.conf

is getting closer -- but it still won't work. It executes the echo command as root -- but echo requires no special privileges, so there's no point in executing it as root. The >> /etc/resolv.conf redirection is executed by your shell, which is running as you, not as root. Since you don't have permission to write to /etc/resolv.conf, the command fails. The sudo command never sees the redirection.

You need the redirection to be executed under the root account, which means that you need a shell process running as root. So the solution is:

sudo sh -c 'echo nameserver 8.8.8.8 >> /etc/resolv.conf'

This launches a shell as a root process. That shell executes the command line echo nameserver 8.8.8.8 >> /etc/resolv.conf. Since you have a root shell executing both the echo and the output redirection, it should work.

(I suggest grabbing a copy of your /etc/resolv.conf file before doing this, just to make sure you can recover if you accidentally clobber it.)

like image 80
Keith Thompson Avatar answered Dec 24 '25 00:12

Keith Thompson