首页 > 解决方案 > golang linux在exec的帮助下添加用户

问题描述

我想使用 golang exec 功能将用户添加到我的服务器,但它不起作用我尝试了多种方法,但找不到有效的解决方案。是不是因为这个?“$(openssl passwd -1 测试)”

这是我的代码

    cmd := exec.Command("sudo", "useradd -p", "$(openssl passwd -1 Test)", "Test1234")
    b, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%s\n", b)

标签: go

解决方案


exec.Command直接运行可执行文件。每个字符串都是一个文字参数。在您的示例中,sudo是程序,您useradd -p作为第一个参数传递,然后$(openssl passwd -1 Test)作为第二个参数传递,依此类推。

useradd -p是它自己的命令,并且不能作为单个字符串参数工作。

$(openssl passwd -1 Test)是 bash(或其他 shell)特定的语法,在exec.Command.

您实际上是在尝试运行三个可执行文件 - sudouseraddopenssl. 您可以在单独的exec.Command调用中运行每个可执行文件,也可以直接运行 shell。

    cmd := exec.Command("openssl", "passwd", "-1", "Test")
    passwordBytes, err := cmd.CombinedOutput()
    if err != nil {
        panic(err)
    }
    // remove whitespace (possibly a trailing newline)
    password := strings.TrimSpace(string(passwordBytes))
    cmd = exec.Command("useradd", "-p", password, "Test1234")
    b, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%s\n", b)

(我建议不要sudo直接在你的 go 代码中运行,因为你正在运行的程序应该直接管理权限。)

要直接运行 shell 以使用$(...)子命令语法,请参阅https://stackoverflow.com/a/24095983/2178159


推荐阅读