2012-08-28 31 views
1

我想将文本添加到只能从特定帐户ID“appid”和passwd“passx”访问的文件中 我试过下面的代码,不行。在Python中运行已更改(已切换)用户的命令行脚本

import os, subprocess 
text=str('23.33%') 
cmd = ['su', 'appid', '-c echo text >> /tofhisfile.txt'] 
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,  stderr=subprocess.PIPE) 
proc.communicate('passx') 

os.system('su appid -c echo text >> /tothisfile.txt') 

回答

1

只能在交互模式下使用su实用程序(或使用expect实用程序以及su身份验证)使用target_user的密码。如果您想使用sudo实用程序将一个用户认证为另一个用户,则应该在/etc/sudoers文件中以root身份编写专用规则(因此您的source_user根本不会被要求输入密码)。另请注意,当您使用sudo时,请使用sudo -u root /bin/sh -c 'echo "root cat write anywhere" > /etc/anywhere',如果是sudo -u root echo "root can write anywhere" > /etc/anywhere,您将收到权限被拒绝的错误。

0

您与shell=True一起使用列表这不起作用。你不想做后者,但即使你做了,shell也会使用字符串,所以你需要与第二个例子相同的字符串。

不管怎么说,你可能只想做这一切的脚本之外。因此,假设您已经正确编辑了setuid(尽管如果您在脚本中执行此操作,将会使用这个命令 - os.setuid),然后只写入该文件,然后使用su whoever -c python mything.py运行该脚本。