如何在 Go 中从用户名切换用户?
我必须使用给定的用户名执行此命令;在 bash 中,
$su devrim -c "touch miki"
我猜,首先我需要从用户名中获取 uid,并在执行 ForkExec 之前使用 setuid。
你可以建议吗?我该怎么做? (ps:我没有 uid,只有用户名)
func exec(cmd *Command, async bool) os.Error {
parts := strings.Fields(cmd.Command)
command := parts[0]
// cmd.Su holds the username "root" or "myUser"
pid, err := os.ForkExec(command, parts, os.Environ(), "", []*os.File{nil, cmd.Stdout, cmd.Stderr})
cmd.Pid = pid
if !async {
os.Wait(pid, 0)
}
return nil
}
编辑:因为 sysuser 的东西不起作用,而且我看到它只是解析 /etc/passwd 我决定自己做:
func getUid(su string) int{
passwd,_ := os.Open("/etc/passwd", os.O_RDONLY , 0600)
reader := bufio.NewReader(passwd)
for {
line,err := reader.ReadString('\n')
if err != nil {
println(err.String())
break
}
parsed := strings.Split(line,":",4)
if parsed[0] == su {
value,_ := strconv.Atoi(parsed[2])
return value
}
}
return -1
}
我不确定是否所有 /etc/passwd 的构成与 *nix 的相同,我们使用 debian 和 ubuntu,请小心操作。
I have to execute this command with given username; in bash it'd be,
$su devrim -c "touch miki"
i guess, first i need to get the uid from the username and use setuid before doing ForkExec.
can u advice? how do i do this ? (ps: i don't have the uid, only username)
func exec(cmd *Command, async bool) os.Error {
parts := strings.Fields(cmd.Command)
command := parts[0]
// cmd.Su holds the username "root" or "myUser"
pid, err := os.ForkExec(command, parts, os.Environ(), "", []*os.File{nil, cmd.Stdout, cmd.Stderr})
cmd.Pid = pid
if !async {
os.Wait(pid, 0)
}
return nil
}
edit: since that sysuser thing didn't work, and i saw that it's only parsing the /etc/passwd i decided to do it myself:
func getUid(su string) int{
passwd,_ := os.Open("/etc/passwd", os.O_RDONLY , 0600)
reader := bufio.NewReader(passwd)
for {
line,err := reader.ReadString('\n')
if err != nil {
println(err.String())
break
}
parsed := strings.Split(line,":",4)
if parsed[0] == su {
value,_ := strconv.Atoi(parsed[2])
return value
}
}
return -1
}
i'm not sure if all /etc/passwd's are formed the same accross *nix's, we use debian and ubuntu, proceed with care.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个包 http://github.com/kless/go-sysuser 可以访问用户名等 。
syscall 包 具有对 Set/Get UID 等的调用
This package http://github.com/kless/go-sysuser can access the usernames, etc.
The syscall package has calls for Set/Get UID, etc.