Search code examples
pythonioprivilegessudohosts-file

IOError: 13, 'Permission denied' when writing to /etc/hosts via Python


I have a Python app that I'm working on that needs to access the hosts file to append a few lines. Everything worked on my test file, but when I told the program to actually modify my hosts file in /etc/hosts I get IOError 13. From what I understand, my app doesn't have root privileges.

My question is, how can I circumnavigate this issue? Is there a way to prompt the user for their password? Would the process be any different if I was running the app on a Windows machine?

Here's the code in question:

f = open("/etc/hosts", "a")
f.write("Hello Hosts File!")

Also, I plan on using py2app and py2exe for the final product. Would they handle the root privilege issue for me?


Solution

  • The easiest way to handle this is to write out your changes to a temp file, then run a program to overwrite the protected file. Like so:

    with open('/etc/hosts', 'rt') as f:
        s = f.read() + '\n' + '127.0.0.1\t\t\thome_sweet_home\n'
        with open('/tmp/etc_hosts.tmp', 'wt') as outf:
            outf.write(s)
    
    os.system('sudo mv /tmp/etc_hosts.tmp /etc/hosts')
    

    When your Python program runs sudo, the sudo program will prompt the user for his/her password. If you want this to be GUI based you can run a GUI sudo, such as "gksu".

    On Windows, the hosts file is buried a couple subdirectories under \Windows. You can use the same general trick, but Windows doesn't have the sudo command. Here is a discussion of equivalents:

    https://superuser.com/questions/42537/is-there-any-sudo-command-for-windows