IOError:13,通过Python写入/ etc / hosts时'权限被拒绝' [英] IOError: 13, 'Permission denied' when writing to /etc/hosts via Python

查看:1391
本文介绍了IOError:13,通过Python写入/ etc / hosts时'权限被拒绝'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我正在研究的Python应用程序需要访问hosts文件以附加几行。一切都在我的测试文件上工作,但是当我告诉程序实际修改/ etc / hosts中的hosts文件时,我得到IOError 13.据我所知,我的应用程序没有root权限。

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.

我的问题是,我该如何绕过这个问题?有没有办法提示用户输入密码?如果我在Windows机器上运行该应用程序,该过程会有所不同吗?

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?

以下是相关代码:

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

另外,我打算在最终产品中使用py2app和py2exe。他们会为我处理root权限问题吗?

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

推荐答案

处理此问题的最简单方法是将您的更改写出来文件,然后运行程序来覆盖受保护的文件。像这样:

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')

当你的Python程序运行sudo时,sudo程序会提示用户输入他/她的密码。如果您希望这是基于GUI的,您可以运行GUI sudo,例如gksu。

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".

在Windows上,hosts文件被隐藏在\下的几个子目录中视窗。您可以使用相同的一般技巧,但Windows没有sudo命令。以下是对等价物的讨论:

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

这篇关于IOError:13,通过Python写入/ etc / hosts时'权限被拒绝'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆