top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration
Print Preview

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

0 votes

I'm trying to write a python 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?

posted Aug 9, 2013 by Salil Agrawal

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

2 Answers

+1 vote

sudo doesn't work like this. It doesn't read from standard input. You need to supply the command as an argument to sudo. Get the sudo syntax correct by learning to use it in a shell (eg terminal running bash )
before trying to use it from python code. Also, I think that passing the pipe character '|' as an argument to Popen is not the correct way to use pipes.

So, if you figure out how to use sudo without '|' you will solve both these issues.

answer Aug 9, 2013 by Sumit Pokharna
Or try to change the permissions

os.system("chmod 666 config_file)

do what you want with the file and set the permissions back to their  original state.
0 votes

Do you find anything with:

$ grep sudo /var/log/auth.log
(you may need to specify a different log)

Is the process that's trying to use the sudo command allowed to do so without a password?

man sudoers

Note - after editing /etc/sudoers you must set the permissions back to 440

answer Aug 9, 2013 by Sheetal Chauhan
Similar Questions
+3 votes

When I tried to run this kind of script unless I exit rest of the script is not getting executed.

0 votes

I need to write into a file for a project which will be evaluated on the basis of time. What is the fastest way to write 200 Mb of data, accumulated as a list into a file.

Presently I am using this:

with open('index.txt','w') as f:

where data is a list of strings which I want to dump into the index.txt file

0 votes

I am a python script which tries to create a file under directory /etc/ but I am getting the error as

IOError: [Errno 13] Permission denied: '/etc/file'

Any Idea how to create a file in /etc as non-root user?

0 votes

How can write a python script which will execute some perl scripts in a gui and shouldn't be post processed....?

Useful Links with Similar Problem
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.