使用来自 python 的根权限编辑文件

Editing a file with root privileges from python

我正在尝试让 python 程序写入受根保护的文件。这是使用 python 通知模块。我正在尝试让程序使用已注册的端点。 在控制台上,它们都可以工作并在文件 /root/.config/notify-run:

中写入一些文本
sudo sh -c 'echo sometext >> /root/.config/notify-run'
echo sometext | sudo tee /root/.config/notify-run

现在 python 我尝试了:

link = 'the endpoint'
command = ['sudo sh -c "echo', link, ' >>/root/.config/notify-run"']
subprocess.call(command, shell=True)

这个returns:

syntax error unterminated quoted string

并尝试:

link = 'the endpoint'
command = ['echo', link, '| sudo tee -a /root/.config/notify-run'] 
subprocess.call(command, shell=True)

Returns没有错误但没有在文件中写入端点。

有人知道如何解决这个问题吗?使用这个或其他与我在这里尝试做的相同的代码?

使用字符串命令而不是数组。这对我有用:

link = 'the endpoint'
command = 'echo ' + link + ' | sudo tee -a /root/.config/notify-run'
subprocess.call(command, shell=True)

但是,我建议您直接编辑 Python 脚本中的 notify-run 文件和 运行 具有 root 权限的整个 Python 脚本,这样您不必 运行 sudo,除非您的脚本不仅仅是写入该文件。

在您的命令中输入 sudo 将显示密码提示,并且可能会在那里失败。

以上答案要求您直接以 root 用户身份 运行 您的脚本,但是,如果这不可能,那么您可以将您的脚本 sudo tee -a /root/.config/notify-run 移动到另一个文件中。

/etc/sudoers 文件中赋予它 sudo 权限并执行它。