getpasswd functionality in Go?

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

    Required launching stty via Go ForkExec() function:

    package main
    
    import (
        os      "os"
        bufio   "bufio"
        fmt     "fmt"
        str     "strings"
    )
    
    func main() {
        fmt.Println();
        if passwd, err := Getpasswd("Enter password: "); err == nil {
            fmt.Printf("\n\nPassword: '%s'\n",passwd)
        }
    }
    
    func Getpasswd(prompt string) (passwd string, err os.Error) {
        fmt.Print(prompt);
        const stty_arg0  = "/bin/stty";
        stty_argv_e_off := []string{"stty","-echo"};
        stty_argv_e_on  := []string{"stty","echo"};
        const exec_cwdir = "";
        fd := []*os.File{os.Stdin,os.Stdout,os.Stderr};
        pid, err := os.ForkExec(stty_arg0,stty_argv_e_off,nil,exec_cwdir,fd);
        if err != nil {
            return passwd, os.NewError(fmt.Sprintf("Failed turning off console echo for password entry:\n\t%s",err))
        }
        rd := bufio.NewReader(os.Stdin);
        os.Wait(pid,0);
        line, err := rd.ReadString('\n');
        if err == nil {
            passwd = str.TrimSpace(line)
        } else {
            err = os.NewError(fmt.Sprintf("Failed during password entry: %s",err))
        }
        pid, e := os.ForkExec(stty_arg0,stty_argv_e_on,nil,exec_cwdir,fd);
        if e == nil {
            os.Wait(pid,0)
        } else if err == nil {
            err = os.NewError(fmt.Sprintf("Failed turning on console echo post password entry:\n\t%s",e))
        }
        return passwd, err
    }
    

提交回复
热议问题