使用python的root权限编辑文件

碧玉

我正在尝试使python程序写入受根保护的文件。这是使用python notify模块。我正在尝试让程序使用注册的端点。在控制台上,这些都可以工作,并在/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)

返回:

syntax error unterminated quoted string

并尝试:

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

不返回错误,但不将端点写入文件。

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

马克·桑斯

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

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

但是,我建议您直接notify-run从Python脚本中编辑文件,然后使用root特权运行整个Python脚本,这样就不必运行sudo,除非您的脚本除了写该文件之外还需要做更多事情。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章