登录
首页 >  Golang >  Go问答

Golang无法成功修改Linux用户密码

来源:stackoverflow

时间:2024-03-09 10:30:26 326浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《Golang无法成功修改Linux用户密码》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我需要 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 上找到了一些类似的示例,但我正在使用在那里找到的解决方案,但它不起作用。


解决方案


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

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

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

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

func main() {
    cmd := exec.command("chpasswd")
    stdin, err := cmd.stdinpipe()
    io.writestring(stdin, "pgc:password")
}

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

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

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

所以有效的代码(基本上是 stdin 示例,做了一些小改动):

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)
}

本篇关于《Golang无法成功修改Linux用户密码》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>