getpasswd functionality in Go?

前端 未结 9 1687
春和景丽
春和景丽 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:32

    Here is a version specific to Linux:

    func terminalEcho(show bool) {
        // Enable or disable echoing terminal input. This is useful specifically for
        // when users enter passwords.
        // calling terminalEcho(true) turns on echoing (normal mode)
        // calling terminalEcho(false) hides terminal input.
        var termios = &syscall.Termios{}
        var fd = os.Stdout.Fd()
    
        if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd,
            syscall.TCGETS, uintptr(unsafe.Pointer(termios))); err != 0 {
            return
        }
    
        if show {
            termios.Lflag |= syscall.ECHO
        } else {
            termios.Lflag &^= syscall.ECHO
        }
    
        if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd,
            uintptr(syscall.TCSETS),
            uintptr(unsafe.Pointer(termios))); err != 0 {
            return
        }
    }
    

    So to use it:

    fmt.Print("password: ")
    
    terminalEcho(false)
    var pw string
    fmt.Scanln(&pw)
    terminalEcho(true)
    fmt.Println("")
    

    It's the TCGETS syscall that is linux specific. There are different syscall values for OSX and Windows.

提交回复
热议问题