Python os.chown(path, uid, gid)
方法用于将path
的所有者和group修改为指定的uid
和gid
。
- 如果不修改可以将uid或gid设置为 -1
- 需要超级用户权限来执行修改操作
- os.chown()方法只在UNIX/LINUX平台上可用
os.chown 语法
os.chown(path, uid, gid, *, dir_fd = None, follow_symlinks = True)
os.chown 参数
- path – 设置权限的文件路径
- uid – 所属用户 ID
- gid – 所属用户组 ID
- dir_fd (可选) – 指向一个目录的FD
- follow_symlinks (可选) – Bool值,默认是True。当为False时,该方法将对符号链接本身而不是链接指向的文件进行操作。
参数列表中的
*
表示所有后面的参数都是关键字参数(在我们例子中是dir_fd
和follow_symlinks
),也就是非位置参数。
os.chown 返回值
os.chown
方法没有返回值。
os.chown 示例1: 简单用法
# Api demos for os.chown() method
import os
path = "apidemos.txt"
# Print the UID and GID of the file
print("UID of the file:", os.stat(path).st_uid)
print("GID of the file:", os.stat(path).st_gid)
os.chown(path, 4000, 4000)
print("\nUID and GID of this file has changed")
# Print the UID and GID of the file again
print("\nOwner id of the file:", os.stat(path).st_uid)
print("Group id of the file:", os.stat(path).st_gid)
输出:
os.chown 示例2: 只修改UID
# Api demos for os.chown() method
import os
path = "apidemos.txt"
# Print the UID and GID of the file
print("UID of the file:", os.stat(path).st_uid)
print("GID of the file:", os.stat(path).st_gid)
os.chown(path, 5000, -1)
print("\nUID of this file has changed")
# Print the UID and GID of the file again
print("\nOwner id of the file:", os.stat(path).st_uid)
print("Group id of the file:", os.stat(path).st_gid)
输出:
os.chown 示例3: 修改符号链接文件本身的UID和GID
# Api demos for os.chown() method
import os
path = "apidemos.txt"
# using os.symlink() method to create a symlink for path
path_symlink = "apidemos_symlink.txt"
os.symlink(path, path_symlink)
# Print the UID and GID of the path and path_symlink
print("UID of the path:", os.stat(path).st_uid)
print("GID of the path:", os.stat(path).st_gid)
print("UID of the path_symlink:", os.stat(path_symlink).st_uid)
print("GID of the path_symlink:", os.stat(path_symlink).st_gid)
# Case 1: change the path_symlink file's UID and GID with default follow_symlinks
os.chown(path_symlink, 4000, 4000)
# Print the UID and GID of the path and path_symlink
print("Case 1: change the path_symlink file's UID and GID with default follow_symlinks to 1000")
print("UID of the path:", os.stat(path).st_uid)
print("GID of the path:", os.stat(path).st_gid)
print("UID of the path_symlink:", os.stat(path_symlink).st_uid)
print("GID of the path_symlink:", os.stat(path_symlink).st_gid)
# Case 2: change the path_symlink file's UID and GID with follow_symlinks=False
os.chown(path_symlink, 3000, 3000, follow_symlinks = False)
# Print the UID and GID of the path and path_symlink
print("Case 2: change the path_symlink file's UID and GID with follow_symlinks=False to 2000")
print("UID of the path:", os.stat(path).st_uid)
print("GID of the path:", os.stat(path).st_gid)
print("UID of the path_symlink:", os.stat(path_symlink).st_uid)
print("GID of the path_symlink:", os.stat(path_symlink).st_gid)
输出:
我们可以看到,当设置follow_symlinks = False
时,执行os.chown只修改的符号链接文件本身的UID和GID,被链接的文件的UID和GID未发生变化。