我需要一个 goroutine 内部的单行代码来更改 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 上找到了一些类似的示例,但我使用的是在那里找到的解决方案,但它不起作用。