IOError:13,“权限被拒绝”通过 Python 写入 /etc/hosts 时
我正在开发一个 Python 应用程序,需要访问主机文件以添加几行。一切都在我的测试文件上运行,但是当我告诉程序实际修改 /etc/hosts 中的主机文件时,我收到 IOError 13。据我了解,我的应用程序没有 root 权限。
我的问题是,我该如何解决这个问题?有没有办法提示用户输入密码?如果我在 Windows 计算机上运行该应用程序,该过程会有什么不同吗?
这是有问题的代码:
f = open("/etc/hosts", "a")
f.write("Hello Hosts File!")
另外,我计划将 py2app 和 py2exe 用于最终产品。他们会帮我处理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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
处理此问题的最简单方法是将更改写入临时文件,然后运行程序来覆盖受保护的文件。就像这样:
当你的Python程序运行sudo时,sudo程序将提示用户输入他/她的密码。如果您希望它是基于 GUI 的,您可以运行 GUI sudo,例如“gksu”。
在 Windows 上,hosts 文件隐藏在 \Windows 下的几个子目录中。您可以使用相同的通用技巧,但 Windows 没有 sudo 命令。以下是等效项的讨论:
https://superuser.com/questions/42537 /是否有适用于 Windows 的 sudo 命令
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:
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
如果您在
sudoers
列表中,则可以使用sudo
启动您的程序:sudo 使用 root 权限运行您的 Python 解释器。
第一次执行此操作时,系统会要求您输入您的密码,以后的调用将不会询问您上次
sudo
调用是否是在不久之前。在 sudoers 列表中(在大多数情况下
/etc/sudoers
)表明管理员信任您。如果您调用sudo
,系统不会要求您提供root
密码,而是您的密码。您必须证明正确的用户位于终端上。有关
sudo
的更多信息,请访问 http://en.wikipedia.org/wiki/Sudo< /a>如果你想远程控制它,你可以使用
-S
命令行开关或使用 http://www.noah.org/wiki/pexpectIf you are on the
sudoers
list, you can start your progamm withsudo
: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 callsudo
you are not asked for theroot
password, but yours. You have to prove that the right user sits at the terminal.More about
sudo
on http://en.wikipedia.org/wiki/SudoIf you want to remote controll this you can use the
-S
command line switch or use http://www.noah.org/wiki/pexpect