Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silence user input in Scan function

Tags:

go

How do I hide user input (password field) in terminal similar to the -s command in read -s p "password " password in bash. ?

var password string
fmt.Println("password: ")
fmt.Scan(&password)

http://play.golang.org/p/xAPDDPjKb4

like image 213
user3918985 Avatar asked May 21 '15 02:05

user3918985


3 Answers

The best way would be to use ReadPassword() from the terminal package. Else you can also look in this question for more ways to do so.

Code example:

package main

import "golang.org/x/crypto/ssh/terminal"
import "fmt"

func main() {
 fmt.Println("Enter password: ")
 password, err := terminal.ReadPassword(0)
 if err == nil {
    fmt.Println("Password typed: " + string(password))
 }
}
like image 109
Bhullnatik Avatar answered Oct 23 '22 04:10

Bhullnatik


I have no idea about go, so I'm not sure if you can call other programs. If so, just call stty -echo to hide input and stty echo to show it again.

Otherwise you could try the following:

fmt.Println("password: ")
fmt.Println("\033[8m") // Hide input
fmt.Scan(&password)
fmt.Println("\033[28m") // Show input
like image 4
Ignasi Avatar answered Oct 23 '22 05:10

Ignasi


To support windows, as mentioned here, please use:

import "syscall"
import "golang.org/x/crypto/ssh/terminal"

passwd, err := terminal.ReadPassword(int(syscall.Stdin))
like image 4
Cedric Zhuang Avatar answered Oct 23 '22 04:10

Cedric Zhuang