gpt4 book ai didi

go - 是否有查找完整文件权限的功能?

转载 作者:行者123 更新时间:2023-12-01 19:47:20 26 4
gpt4 key购买 nike

我需要使用 Go 获取给定文件的文件权限(特别是 SUID 位)。以下是示例文件的权限。

$ touch example_file.test
$ chmod 7777 example_file.test
$ ls -ltra example_file.test
-rwsrwsrwt 1 luke users 0 Feb 25 21:53 example_file.test

$ stat -c "%a %n" example_file.test
7777 example_file.test

这是一个说明问题的小程序。

func main() {
info, _ := os.Stat("example_file.test")
fmt.Println(info.Mode().String()) // ugtrwxrwxrwx
fmt.Println(info.Mode().Perm().String()) // -rwxrwxrwx
fmt.Printf("permissions: %#o\n", info.Mode().Perm()) // permissions: 0777
}

Go 结果不一致,因为 ugtrwxrwxrwx != 0777

文档中的以下引述表明这可能是一个跨平台兼容性问题。

A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is ModeDir for directories.

type FileMode uint32 The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

这是 Go 的局限性吗?

最佳答案

值得注意的是,除了八进制表示不匹配外,字符串表示也不匹配:

"-rwsrwsrwt" != "ugtrwxrwxrwx"`

这不是由于 Go 实现的限制,而是它以与系统无关的方式实现的结果。

来自 the FileMode documentation (强调我的):

A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems.

由于实现并非旨在模仿特定系统的行为,因此不能保证输出与给定环境中的 native 工具相匹配。但是,所有相关数据都可以使用。

如果您想模仿 stat 的输出,您只需编写一些逻辑即可。

这是一个处理八进制表示的简单示例:

package main

import (
"fmt"
"os"
)

func UnixPerm(m os.FileMode) (p uint32) {
p = uint32(m.Perm())
if m & os.ModeSetuid != 0 {
p |= 04000
}
if m & os.ModeSetgid != 0 {
p |= 02000
}
if m & os.ModeSticky != 0 {
p |= 01000
}
return p
}

func main() {
info, _ := os.Stat("example_file")
fmt.Printf("FileMode.Perm(): %04o\n", info.Mode().Perm())
fmt.Printf("UnixPerm(): %04o\n", UnixPerm(info.Mode()))
}

输出:

$ go run fileperm.go
FileMode.Perm(): 0777
UnixPerm(): 7777

$ stat --printf "Permissions: %a\n" example_file
Permissions: 7777

关于go - 是否有查找完整文件权限的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com