Go语言获取操作系统用户信息

桃扇骨 2023-10-03 10:06 27阅读 0赞

一、os包结构介绍

  • Go语言标准库中os包提供了不依赖平台的操作系统接口
  • 设计为Unix风格的,而错误处理是go风格的,失败的调用会返回错误值而非错误码。通常错误值里包含更多信息
  • os包及子包功能
  1. -- os
  2. --os/exec 包,负责执行外部命令.
  3. --os/signal对输入信息的访问
  4. --os/user 通过名称或ID 查询用户账户

在os/user中提供了User结构体,表示操作系统用户

  • Uid 用户id
  • Gid 所属组id
  • Username 用户名
  • Name 所属组名
  • HomeDir 用户对应文件夹路径
  1. // User represents a user account.
  2. type User struct {
  3. // Uid is the user ID.
  4. // On POSIX systems, this is a decimal number representing the uid.
  5. // On Windows, this is a security identifier (SID) in a string format.
  6. // On Plan 9, this is the contents of /dev/user.
  7. Uid string
  8. // Gid is the primary group ID.
  9. // On POSIX systems, this is a decimal number representing the gid.
  10. // On Windows, this is a SID in a string format.
  11. // On Plan 9, this is the contents of /dev/user.
  12. Gid string
  13. // Username is the login name.
  14. Username string
  15. // Name is the user's real or display name.
  16. // It might be blank.
  17. // On POSIX systems, this is the first (or only) entry in the GECOS field
  18. // list.
  19. // On Windows, this is the user's display name.
  20. // On Plan 9, this is the contents of /dev/user.
  21. Name string
  22. // HomeDir is the path to the user's home directory (if they have one).
  23. HomeDir string
  24. }

在os/user中的Group表示用户所属组

  • Gid 组的id
  • Name 组的名称
  1. // Group represents a grouping of users.
  2. //
  3. // On POSIX systems Gid contains a decimal number representing the group ID.
  4. type Group struct {
  5. Gid string // group ID
  6. Name string // group name
  7. }

整个os/user包中内容比较少,提供了两个错误类型和获取当前用户,查找用户

  1. type UnknownUserError
  2. func (e UnknownUserError) Error() string
  3. type UnknownUserIdError
  4. func (e UnknownUserIdError) Error() string
  5. type User
  6. func Current() (*User, error)
  7. func Lookup(username string) (*User, error)
  8. func LookupId(uid string) (*User, error)

二、代码示例

可以获取当前用户或查找用户后获取用户信息

  1. //获取当前登录用户
  2. //u,_:=user.Current()
  3. /*
  4. Lookup()参数是用户名,按照用户名查找指定用户对象
  5. 注意:必须使用完整名称不可以只写zhang
  6. */
  7. u, _ := user.Lookup(`LAPTOP-M7D47U95\zhang`)
  8. fmt.Println(u.Name)
  9. fmt.Println(u.Gid)
  10. fmt.Println(u.HomeDir)
  11. fmt.Println(u.Uid)
  12. fmt.Println(u.Username)

发表评论

表情:
评论列表 (有 0 条评论,27人围观)

还没有评论,来说两句吧...

相关阅读

    相关 c# 获取服务器操作系统信息

    软件部署到多个服务器上时,我们需要做一些校验,比如有效期的校验,这就可能关联很多操作系统的物理参数,通过以下 方法可以获取一些相关参数,然后后通过UPD发包到控制中心,同时还