getpasswd functionality in Go?

前端 未结 9 1659
春和景丽
春和景丽 2020-12-02 13:08

Situation:

I want to get a password entry from the stdin console - without echoing what the user types. Is there something com

相关标签:
9条回答
  • 2020-12-02 13:41

    you can do this by execing stty -echo to turn off echo and then stty echo after reading in the password to turn it back on

    0 讨论(0)
  • 2020-12-02 13:44

    I had a similar usecase and the following code snippet works well for me. Feel free to try this if you are still stuck here.

    import (
        "fmt"
        "golang.org/x/crypto/ssh/terminal"
    
    )
    
    func main() {
        fmt.Printf("Now, please type in the password (mandatory): ")
        password, _ := terminal.ReadPassword(0)
    
        fmt.Printf("Password is : %s", password)
    }
    

    Of course, you need to install terminal package using go get beforehand.

    0 讨论(0)
  • 2020-12-02 13:44

    You can get the behavior you want with the Read method from the os.File object (or the os.Stdin variable). The following sample program will read a line of text (terminated with by pressing the return key) but won't echo it until the fmt.Printf call.

    package main
    
    import "fmt"
    import "os"
    
    func main() {
      var input []byte = make( []byte, 100 );
      os.Stdin.Read( input );
      fmt.Printf( "%s", input );
    }
    

    If you want more advanced behavior, you're probably going to have to use the Go C-wrapper utilities and create some wrappers for low-level api calls.

    0 讨论(0)
提交回复
热议问题