我正在尝试使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)
不返回错误,但不将端点写入文件。
有人知道如何解决此问题吗?使用此代码或其他与我在此处尝试执行的代码相同的代码?
答案 0 :(得分:2)
使用字符串命令而不是数组。这对我有用:
link = 'the endpoint'
command = 'echo ' + link + ' | sudo tee -a /root/.config/notify-run'
subprocess.call(command, shell=True)
但是,我建议您直接从Python脚本中编辑notify-run
文件,并以root
特权运行整个Python脚本,这样就不必运行sudo
,除非您的脚本所要做的不只是写入该文件。
答案 1 :(得分:0)
在命令中键入sudo
会显示密码提示,并且可能会在此提示失败。
以上答案要求您直接以root用户身份运行脚本,但是,如果不可能,则可以将脚本sudo tee -a /root/.config/notify-run
移动到另一个文件中。
授予/etc/sudoers
文件中的sudo访问权限并执行它。