python - 通过Python写入/etc/hosts时IOError : 13, 'Permission denied'

标签 python io privileges sudo hosts-file

我有一个正在开发的 Python 应用程序,它需要访问主机文件以附加几行。一切都在我的测试文件上运行,但是当我告诉程序实际修改/etc/hosts 中的主机文件时,我得到 IOError 13。据我了解,我的应用程序没有根权限。

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

这是有问题的代码:

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

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

最佳答案

处理此问题的最简单方法是将更改写入临时文件,然后运行程序覆盖 protected 文件。像这样:

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”。

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

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

关于python - 通过Python写入/etc/hosts时IOError : 13, 'Permission denied',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7510617/

相关文章:

python - 将大型数据框拆分为较小的 Pandas 数据框列表

python - 如何在python中获得两个向量的相关性

python - 使用 Playwright for Python,如何选择(或查找)一个元素?

java - 基于异步队列的文件写入

process - 在 Elixir 任务中获取用户输入

python - 在 Django 中创建用户 : User, Staff, SuperUser

C# 即使具有管理员权限也无法访问系统文件

python - IndexView 缺少 QuerySet。定义 IndexView.model - tutorial 4 django

C++ 字符串文件重定向差异?

mysql - 在MySQL中创建用户而不删除、更新和更改权限