tags:

views:

62

answers:

1

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.

+2  A: 

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

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

cthom06
thx cthom! although it throws an error and doesn't install, it definitely is what i'm looking for.
Devrim
@Devrim ahh, well I haven't actually used it. But it may just be a makefile issue or just need a minor change to be in sync with the latest go release
cthom06
sysuser was only parsing, no native go method to do it. so i parsed it myself - solution is above. thx again!
Devrim