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

一、os包结构介绍

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

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

  • Uid 用户id
  • Gid 所属组id
  • Username 用户名
  • Name 所属组名
  • HomeDir 用户对应文件夹路径
// User represents a user account.
type User struct {
	// Uid is the user ID.
	// On POSIX systems, this is a decimal number representing the uid.
	// On Windows, this is a security identifier (SID) in a string format.
	// On Plan 9, this is the contents of /dev/user.
	Uid string
	// Gid is the primary group ID.
	// On POSIX systems, this is a decimal number representing the gid.
	// On Windows, this is a SID in a string format.
	// On Plan 9, this is the contents of /dev/user.
	Gid string
	// Username is the login name.
	Username string
	// Name is the user's real or display name.
	// It might be blank.
	// On POSIX systems, this is the first (or only) entry in the GECOS field
	// list.
	// On Windows, this is the user's display name.
	// On Plan 9, this is the contents of /dev/user.
	Name string
	// HomeDir is the path to the user's home directory (if they have one).
	HomeDir string
}

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

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

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

type UnknownUserError
  func (e UnknownUserError) Error() string
type UnknownUserIdError
  func (e UnknownUserIdError) Error() string
type User
  func Current() (*User, error)
  func Lookup(username string) (*User, error)
  func LookupId(uid string) (*User, error)

二、代码示例

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

 //获取当前登录用户
 //u,_:=user.Current()
 /*
 Lookup()参数是用户名,按照用户名查找指定用户对象
 注意:必须使用完整名称不可以只写zhang
  */
 u, _ := user.Lookup(`LAPTOP-M7D47U95\zhang`)
 fmt.Println(u.Name)
 fmt.Println(u.Gid)
 fmt.Println(u.HomeDir)
 fmt.Println(u.Uid)
 fmt.Println(u.Username)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书香水墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值