GO:ssh进入Unix获取用户/etc/passwd并查找与每个用户相关联的组[关闭]

lnxxn5zx  于 2023-05-11  发布在  Go
关注(0)|答案(1)|浏览(126)

已关闭,此问题需要更focused。目前不接受答复。
**想改善这个问题吗?**更新问题,使其仅通过editing this post关注一个问题。

3天前关闭。
Improve this question
我是新来的Golang。我可以从cat /etc/passwd中获取用户列表。我试图实现的是,对于cat /etc/passwd返回的每个用户,我希望运行“id -user”命令并将用户组Map到该用户。我应该使用什么数据结构?或
有没有一个Shell命令,我可以得到火来实现上述?我试过这个-
对于$(awk -F:/etc/passwd); do groups $user;完成

tail -n +1-F /etc/passwd|头-n +2500 -f”:“/etc/passwd

qoefvg9y

qoefvg9y1#

我应该使用什么数据结构?
你可以使用任何东西,从数组,列表,Map,字典到任何东西,这里没有特定的数据结构选择约束。在这里,代码提供了一个map数据结构的示例,其中包含string的混合。关于shell命令,os/exec包提供了这里需要的功能(exec.Command)。在Playground:中运行代码

package main

import (
    "bufio"
    "fmt"
    "os"
    "os/exec"
    "strings"
)

type UserGroups map[string][]string

func main() {
    file, err := os.Open("/etc/passwd")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)

    userGroups := make(UserGroups)

    for scanner.Scan() {
        fields := strings.Split(scanner.Text(), ":")

        username := fields[0]

        cmd := exec.Command("id", "-Gn", username)
        output, err := cmd.Output()
        if err != nil {
            panic(err)
        }

        groups := strings.Split(strings.TrimSpace(string(output)), " ")

        userGroups[username] = groups
    }

    for username, groups := range userGroups {
        fmt.Printf("%s: %s\n", username, strings.Join(groups, ", "))
    }
}

Playground输出:

operator: operator
mail: mail
www-data: www-data
bin: bin
sys: sys
sync: users
nobody: nobody
root: root, wheel
daemon: daemon

Program exited.

相关问题