dtsc14683 2010-10-13 03:03
浏览 290
已采纳

如何在Go中从用户名切换用户?

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('
')
        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.

  • 写回答

1条回答 默认 最新

  • duandu2159 2010-10-13 04:46
    关注

    This package http://github.com/kless/go-sysuser can access the usernames, etc.

    The syscall package has calls for Set/Get UID, etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退