Go fmt.Scanln不会回显用户输入的字符。用于密码输入。

huangapple go评论120阅读模式
英文:

Go fmt.Scanln that doesn't echo back characters typed by user. For password

问题

如何在命令行中捕获用户输入,而不回显用户输入的字符。我想用这个方法来捕获密码,就像Python中的getpass.getpass函数一样。

  1. package main
  2. import (
  3. "fmt"
  4. "golang.org/x/term"
  5. )
  6. func main() {
  7. fmt.Print("Enter password: ")
  8. password, _ := term.ReadPassword(0)
  9. fmt.Println("\nPassword entered:", string(password))
  10. }

在上面的示例中,我们使用golang.org/x/term包中的ReadPassword函数来捕获密码输入。该函数会在用户输入密码时隐藏字符,并返回输入的密码。

英文:

How do I capture user input from the command line without echoing back the characters that the user types. I want to use this to capture a password. Like getpass.getpass in Python.

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. var password string
  7. fmt.Scanln(&password)
  8. }

答案1

得分: 3

标准库中没有这个功能的辅助函数。

你需要创建自己的函数,或者使用现有的函数库,比如 gopass(支持Windows、Unix、BSD)。

使用gopass:(示例来自他们的网站)

  1. import "fmt"
  2. import "github.com/howeyc/gopass"
  3. func main() {
  4. fmt.Printf("Password: ")
  5. pass := gopass.GetPasswd() // 静默模式,使用 gopass.GetPasswdMasked() 来显示 *
  6. // 处理密码
  7. }
英文:

There is no helper function in the standard library for this.

You have to create your own, or use an existing one like gopass (supports windows, unix, bsd).

Using gopass: (example taken from their website)

  1. import "fmt"
  2. import "github.com/howeyc/gopass"
  3. func main() {
  4. fmt.Printf("Password: ")
  5. pass := gopass.GetPasswd() // Silent, for *'s use gopass.GetPasswdMasked()
  6. // Do something with pass
  7. }

huangapple
  • 本文由 发表于 2015年2月2日 16:49:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/28273904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定