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

I have a Python application I'm working on, it needs to access the hosts file in order to add a few lines. Everything worked on my test file, but when I told the program to actually change my hosts file in / etc / hosts, I get IOError 13. From what I understand, my application does not have root privileges.

My question is, how can I get around this problem? Is there a way to ask the user for a password? Will the process be different if I run the application on a Windows computer?

Here is the code in question:

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

In addition, I plan to use py2app and py2exe for the final product. Will they handle the root issue for me?

+4
source share
2 answers

The easiest way to handle this is to write your changes to a temporary file, and then run the program to overwrite the protected file. For instance:

 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 starts sudo, the sudo program will prompt the user to enter a password. If you want this to be based on a graphical interface, you can run the sudo GUI, such as "gksu".

On Windows, the hosts file is like a pair of subdirectories in \ Windows. You can use the same general trick, but Windows does not have a sudo command. Here is a discussion of equivalents:

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

+5
source

If you are on the sudoers list, you can run your program using sudo :

  sudo python append_to_host.py 

sudo runs your python interpreter with root privileges. The first time you do this, you will be prompted to enter a password, no further calls will ask you if your last call to sudo not so long ago.

The list of sudoers (in most cases /etc/sudoers ) says that the administrator trusts you. If you call sudo , you are not asked for the root password, but yours. You must prove that the correct user is sitting on the terminal.

Learn more about sudo at http://en.wikipedia.org/wiki/Sudo

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

+6
source

All Articles