2012-08-28 32 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運行該腳本。