【问题标题】:golang linux add an user with help of execgolang linux在exec的帮助下添加用户
【发布时间】:2021-03-29 21:41:35
【问题描述】:

我想使用 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)

【问题讨论】:

  • 分开useradd-p

标签: go


【解决方案1】:

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)

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

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

【讨论】:

  • 你好,它的返回用户添加:无效字段'$1$Gu9wY7nT$.Tl39zCwvI3.I1bV0rg.b1'
  • 这将是您使用useradd 的问题。确保您尝试运行的任何内容也可以在终端上运行。看来您需要先使用 crypt 加密密码,使用 -p 选项 - linux.die.net/man/8/useradd
  • 但是为什么它可以在终端上运行而不是在 go 中呢?当我输入useradd -p $1$eHZrL9Px$RgxlN19Wu1S/yV8auzDeE/ Test 时,它可以工作
  • 我不知道。 $ 字符是否被您的外壳扩展? (如果将密码字符串用单引号括起来,它的行为是否相同?)
  • 我找到了解决方案。 a := strings.TrimSpace(string(password)) 成功了
猜你喜欢
  • 1970-01-01
  • 2012-06-14
  • 2021-05-05
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 2010-11-27
  • 1970-01-01
相关资源
最近更新 更多