我有一个简单的python脚本,名为myCreate.py,在linux上运行:
fo = open("./testFile.txt", "wb")
当我运行python ./myCreate.py – testFile.txt的所有者保留我的用户。 当我运行sudo python ./myCreate.py – testFile.txt的所有者现在是root。
testFile.txt以前没有运行过这两个执行
我怎么能使文件的所有者保持真正的用户,而不是有效的用户? 谢谢!
用sudo运行你的脚本意味着你以root身份运行它。 所以这是正常的,你的文件由root拥有。
你可以做的是在创建文件后更改文件的所有权。 为了做到这一点,你需要知道哪个用户运行sudo。 幸运的是,当你使用sudo的时候,有一个SUDO_UID
环境变量。
所以,你可以这样做:
import os print(os.environ.get('SUDO_UID'))
然后,你需要改变文件的所有权 :
os.chown("path/to/file", uid, gid)
如果我们把它放在一起:
import os uid = int(os.environ.get('SUDO_UID')) gid = int(os.environ.get('SUDO_GID')) os.chown("path/to/file", uid, gid)
当然,你会希望它作为一个函数,因为它更方便,所以:
import os def fix_ownership(path): """Change the owner of the file to SUDO_UID""" uid = os.environ.get('SUDO_UID') gid = os.environ.get('SUDO_GID') if uid is not None: os.chown(path, int(uid), int(gid)) def get_file(path, mode="a+"): """Create a file if it does not exists, fix ownership and return it open""" # first, create the file and close it immediatly open(path, 'a').close() # then fix the ownership fix_ownership(path) # open the file and return it return open(path, mode)
用法:
# If you just want to fix the ownership of a file without opening it fix_ownership("myfile.txt") # if you want to create a file with the correct rights myfile = get_file(path)
编辑:更新我的答案感谢@Basilevs,@Robᵩ和@ 5gon12eder
使用os.chown()
,使用os.environ
找到适当的用户ID:
import os fo = open("./testFile.txt", "wb") fo.close() os.chown('./testFile.txt', int(os.environ['SUDO_UID']), int(os.environ['SUDO_GID']))
如何使用os.stat
首先获得包含文件夹的权限,然后将它们应用到文件创建后。
这看起来像(使用python2):
import os path = os.getcwd() statinfo = os.stat(path) fo = open("./testFile.txt", "wb") fo.close() euid = os.geteuid() if (euid == 0) # Check if ran as root, and set appropriate permissioning afterwards to avoid root ownership os.chown('./testFile.txt', statinfo.st_uid, statinfo.st_gid)
正如Elliot所指出的那样,如果您要同时创建多个文件,那么这个功能就会更好。