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

Parker picture Parker · Sep 22, 2011 · Viewed 10.1k times · Source

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?

Answer

rocksportrocker picture rocksportrocker · Sep 22, 2011

If you are on the sudoers list, you can start your progamm with sudo:

 sudo python append_to_host.py

sudo runs your python interpreter with root privileges. The first time you do it, you will be asked for your password, later calls will not ask you if your last sudo call is not to long ago.

Being on the sudoers list (in most cases /etc/sudoers) says that the admin trusts you. If you call sudo you are not asked for the root password, but yours. You have to prove that the right user sits at the terminal.

More about sudo on http://en.wikipedia.org/wiki/Sudo

If you want to remote controll this you can use the -S command line switch or use http://www.noah.org/wiki/pexpect