【问题标题】:Changing linux user password from Golang not working从 Golang 更改 linux 用户密码不起作用
【发布时间】:2021-01-11 11:51:34
【问题描述】:

我需要一个 go 例程中的单行代码来更改 linux 中的用户密码。

从命令行运行的命令:

      echo 'pgc:password' | sudo chpasswd  //"pgc" is the username and "password" 
                                           // is the password I'm changing it to. 

但这不适用于我的 Go 程序。我尝试过替换其他单行命令,例如: drm file.txt、touch file.txt等

这些都有效。

Go 程序位于一个大项目的一个包中,但我现在只是尝试直接从命令行运行它(不用作函数,而是一个独立的 .go 文件)。

我的代码:

    //I have tried changing back and forth between the package that changesystempassword.go is in 
    // and main, but that has no effect

    package main //one-liners DON'T WORK if package is the package this go file is in

    import (
        "fmt"
        "os/exec"
        //"time"
    )

    func main() {
        err := exec.Command("echo", "'pgc:password'", "|", "sudo", "chpasswd).Run()

        //time.sleep(time.Second) - tried adding a sleep so it would have time?

        if err != nil {
            fmt.Println("Password change unsuccessful"
        } else {
            fmt.Println("Password change successful")
        }
    }

程序运行时的结果(命令行中的./changesystempassword)是命令行显示“密码更改成功”。但猜猜怎么了。它没有改变。我在网上和 Stack Exchange 上找到了一些类似的示例,但我正在使用在那里找到的解决方案,但它不起作用。

【问题讨论】:

    标签: linux passwords go


    【解决方案1】:

    谢谢赫尔曼。我的误解有点微妙。我花了很长时间试图得到你引导我工作的例子。直到一位同事建议我在参数传递给命令后抛出一个 \n,它才最终起作用。

    所以有效的代码(基本上是那个标准输入的例子,有一点小改动):

    cmd := exec.Command("sudo", "chpasswd")
    stdin, err := cmd.StdinPipe()
    if err != nil {
        log.Fatal(err)
    }
    
    go func() {
        defer stdin.Close()
        io.WriteString(stdin, "pgc:password\n")
    }()
    
    out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatal(err)
    }
    

    【讨论】:

      【解决方案2】:

      documentation 表示“使用给定参数执行指定程序”。甚至还有一个具体的段落:

      与来自 C 和其他语言的“系统”库调用不同,os/exec 包有意不调用系统 shell,也不扩展任何 glob 模式或处理通常由 shell 完成的其他扩展、管道或重定向。

      所以问题中的代码执行echo,参数为'pgc:password'|sudochpasswd。这是成功的,因为echo 可以完全打印这四个字符串。

      解决办法是直接启动chpasswd,写入其标准输入。这是一个最小的例子:

      func main() {
          cmd := exec.Command("chpasswd")
          stdin, err := cmd.StdinPipe()
          io.WriteString(stdin, "pgc:password")
      }
      

      我建议调整官方example中显示的代码,以获得带有错误检查的安全代码。

      您也可以使用sudo chpasswd 代替chpasswd。请记住,sudo 在这种情况下将无法要求输入密码。一种解决方法是在适当的情况下使用 NOPASSWD 配置 sudoers。

      【讨论】:

      • 感谢您的回复。我已经尝试了几个小时来理解这一点,但我没有得到它。我无法弄清楚“直接启动 chpasswd”是什么意思。如果不使用“echo”,chpasswd 命令在命令行上不起作用。我试图将我的命令合并到您链接到的示例中,但我无法理解这里的一些基本概念。
      • 你可能不知道standard streams。在交互式外壳中,管道运算符| 获取左侧程序的输出(stdout)并将其馈送到右侧程序的输入(stdin)。我在答案中添加了一个最小的、未经测试的示例。
      猜你喜欢
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      • 2015-08-06
      • 2016-12-11
      • 1970-01-01
      相关资源
      最近更新 更多