Using sudo to write to a file as root from a script

Antoon Pardon antoon.pardon at rece.vub.ac.be
Fri Aug 9 09:52:38 EDT 2013


Op 09-08-13 06:11, Adam Mercer schreef:
> Hi
> 
> I'm trying to write a script that writes some content to a file root
> through sudo, but it's not working at all. I am using:
> 
>   channel = 'stable'
>   config_file = '/opt/ldg/etc/channel.conf'
>   command = ['echo', '-n', channel, '|', 'sudo', 'tee', config_file]
>   p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>   out, _ = p.communicate()
> 
> But it seems as if this isn't doing anything.
> 
> I just want to write the contents of the variable channel to the file
> /opt/ldg/etc/channel.conf. But whatever I try just doesn't work. Can
> anyone offer any pointers?
> 
> Cheers
> 
> Adam

subprocess.Popen by default doesn't use a shell. That could mean that
the equivallent shell command you are trying to execute is:

  echo -n stable '|' sudo tee /opt/ldg/etc/channel.conf

instead of

  echo -n stable | sudo tee /opt/ldg/etc/channel.conf

which you probably want.


You should also take care with the echo command. Echo is
usually a shell builtin that can behave differently than
the echo command. You should make sure you are using the
one you actually want to use.

-- 
Antoon Pardon



More information about the Python-list mailing list