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

杀马特。学长 韩版系。学妹 提交于 2019-11-30 15:39:39
steveha

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!