ABR*_*ABR 7 python linux file owner
我在linux上运行了一个名为myCreate.py的简单python脚本:
fo = open("./testFile.txt", "wb")
当我运行python ./myCreate.py时 - testFile.txt的所有者仍然是我的用户.当我运行sudo python ./myCreate.py时 - testFile.txt的所有者现在是root.
以前没有对两个执行运行testFile.txt
如何让文件的所有者保持真实的用户而不是有效的用户?!谢谢!
使用sudo运行脚本意味着您以root身份运行它.所以你的文件归root所有是正常的.
您可以做的是在创建文件后更改文件的所有权.为此,您需要知道哪个用户运行sudo.幸运的是,SUDO_UID使用sudo时会设置一个环境变量.
所以,你可以这样做:
import os
print(os.environ.get('SUDO_UID'))
Run Code Online (Sandbox Code Playgroud)
然后,您需要更改文件所有权:
os.chown("path/to/file", uid, gid)
Run Code Online (Sandbox Code Playgroud)
如果我们把它放在一起:
import os
uid = int(os.environ.get('SUDO_UID'))
gid = int(os.environ.get('SUDO_GID'))
os.chown("path/to/file", uid, gid)
Run Code Online (Sandbox Code Playgroud)
当然,你会希望它作为一个功能,因为它更方便,所以:
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)
Run Code Online (Sandbox Code Playgroud)
用法:
# 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)
Run Code Online (Sandbox Code Playgroud)
编辑:感谢@Basilevs,@Robᵩ和@ 5gon12eder更新了我的答案