Search code examples
pythonfilesubprocesssudo

How to write a file with sudo privileges in Python?


I want to write content to a file with python. The file's location is in the root directory path: /etc/hosts

Below are the file permissions

-rw-r--r--  1 root root

I want to update this file, and it can be only updated with sudo. So I have written the following script:

path = "/etc/hosts"
fr = open(path,'r')
b = fr.read()
b = b+'something to write'
fr.close()
fw = open(path,'w')
fw = os.system('echo %s|sudo -S python %s' % ('root', fw.write(b)))

But I'm getting permission denied error:

IOError: [Errno 13] Permission denied: u'/etc/hosts'

I also tried with subprocess:

os.popen("sudo -S %s"%(open(path,'w')), 'w').write(admin_password)

But this again did not work.

How do I resolve this?


Solution

  • Following solution worked for me finally. I created a new file called etcedit.py which will write to the file.

    os.system("echo %s| sudo -S python etcedit.py %s"  % ('rootpassword', 'host_name'))
    

    My etcedit.py file

    import os, subprocess
    import sys
    from sys import argv
    
    def etc_update(host_name, *args):
        path = "/etc/hosts"
        host_name = host_name[0]
        fw = open(path,'w')
        fw.write(host_name)
    
    etc_update(sys.argv[1:])
    

    This works!