getpasswd functionality in Go?









up vote
34
down vote

favorite
10












Situation:



I want to get a password entry from the stdin console - without echoing what the user types. Is there something comparable to getpasswd functionality in Go?



What I tried:



I tried using syscall.Read, but it echoes what is typed.










share|improve this question























  • The ForkExec() call that was used to implement a solution based on invoking 'stty -echo' is now in the syscall package and takes two fewer arguments than previously.
    – RogerV
    Jul 17 '11 at 4:15














up vote
34
down vote

favorite
10












Situation:



I want to get a password entry from the stdin console - without echoing what the user types. Is there something comparable to getpasswd functionality in Go?



What I tried:



I tried using syscall.Read, but it echoes what is typed.










share|improve this question























  • The ForkExec() call that was used to implement a solution based on invoking 'stty -echo' is now in the syscall package and takes two fewer arguments than previously.
    – RogerV
    Jul 17 '11 at 4:15












up vote
34
down vote

favorite
10









up vote
34
down vote

favorite
10






10





Situation:



I want to get a password entry from the stdin console - without echoing what the user types. Is there something comparable to getpasswd functionality in Go?



What I tried:



I tried using syscall.Read, but it echoes what is typed.










share|improve this question















Situation:



I want to get a password entry from the stdin console - without echoing what the user types. Is there something comparable to getpasswd functionality in Go?



What I tried:



I tried using syscall.Read, but it echoes what is typed.







passwords stdin go getpasswd






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 4:07









Rene Knop

1,1721521




1,1721521










asked Jan 26 '10 at 3:25









RogerV

2,40342132




2,40342132











  • The ForkExec() call that was used to implement a solution based on invoking 'stty -echo' is now in the syscall package and takes two fewer arguments than previously.
    – RogerV
    Jul 17 '11 at 4:15
















  • The ForkExec() call that was used to implement a solution based on invoking 'stty -echo' is now in the syscall package and takes two fewer arguments than previously.
    – RogerV
    Jul 17 '11 at 4:15















The ForkExec() call that was used to implement a solution based on invoking 'stty -echo' is now in the syscall package and takes two fewer arguments than previously.
– RogerV
Jul 17 '11 at 4:15




The ForkExec() call that was used to implement a solution based on invoking 'stty -echo' is now in the syscall package and takes two fewer arguments than previously.
– RogerV
Jul 17 '11 at 4:15












9 Answers
9






active

oldest

votes

















up vote
7
down vote



accepted










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






share|improve this answer


















  • 1




    Thanks for this clue to use stty (am more familiar with Windows than *nix). Note in the source code solution I provide, I needed to specificaly use Go's ForkExec() call. The ordinary Exec() call replaces the current process with stty process.
    – RogerV
    Jan 26 '10 at 8:23






  • 1




    The Go ForkExec() call is now in syscall package and takes two fewer arguments.
    – RogerV
    Jul 17 '11 at 4:16

















up vote
59
down vote













The following is one of best ways to get it done.
First get terminal package by go get golang.org/x/crypto/ssh



package main

import (
"bufio"
"fmt"
"os"
"strings"
"syscall"

"golang.org/x/crypto/ssh/terminal"
)

func main()
username, password := credentials()
fmt.Printf("Username: %s, Password: %sn", username, password)


func credentials() (string, string)
reader := bufio.NewReader(os.Stdin)

fmt.Print("Enter Username: ")
username, _ := reader.ReadString('n')

fmt.Print("Enter Password: ")
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err == nil
fmt.Println("nPassword typed: " + string(bytePassword))

password := string(bytePassword)

return strings.TrimSpace(username), strings.TrimSpace(password)



http://play.golang.org/p/l-9IP1mrhA






share|improve this answer






















  • This should work on windows? I'm keep getting "panic: The handle is invalid" for this.
    – Shikloshi
    Oct 20 '15 at 13:43










  • @Shikloshi I tried this on Ubunut with go version go1.5.1 linux/amd64, and it's working perfectly. Also I think it should work on Windows as well, but didn't check. You can't run it on play golang since we can't install custom packages.
    – gihanchanuka
    Oct 20 '15 at 13:58






  • 9




    It didn't work because of the wrong assumption that 0 is stdin handler in windows (which is not), you can make this code work cross-platform by using terminal.ReadPassword(int(syscall.Stdin)) instead of 0. Thanks a lot, for my opinion the best implementation.
    – Shikloshi
    Oct 20 '15 at 14:47











  • Does this handle UTF8?
    – Ztyx
    Feb 16 '16 at 21:48






  • 3




    you may not want to trim space from password?
    – Senthil Kumar
    Feb 16 at 8:53

















up vote
27
down vote













Just saw a mail in #go-nuts maillist. There is someone who wrote quite a simple go package to be used. You can find it here: https://github.com/howeyc/gopass



It something like that:



package main

import "fmt"
import "github.com/howeyc/gopass"

func main()
fmt.Printf("Password: ")
pass := gopass.GetPasswd()
// Do something with pass






share|improve this answer
















  • 7




    Note, this package uses terminal.MakeRaw from the Go Author's golang.org/x/crypto/ssh/terminal package. That can be used directly if desired.
    – Dave C
    Jul 23 '15 at 14:08






  • 8




    Oh, and there is also terminal.ReadPassword.
    – Dave C
    Jul 23 '15 at 14:14










  • Yeah, that package is a bit silly.
    – Tincho
    May 3 '16 at 19:24

















up vote
2
down vote













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 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.






share|improve this answer






















  • The Go Author's golang.org/x/crypto/ssh/terminal package does this exact thing but handles all the OSes supported by Go. (E.g. by using syscall.TIOCSETA instead of syscall.TCSETS for BSD and using kernel32.dll on Windows).
    – Dave C
    Jul 23 '15 at 14:12

















up vote
2
down vote













Here is a solution that I developed using Go1.6.2 that you might find useful.



It only uses the following standard packages: bufio, fmt, os, strings and syscall. More specifically, it uses syscall.ForkExec() and syscall.Wait4() to invoke stty to disable/enable terminal echo.



I have tested it on Linux and BSD (Mac). It will not work on windows.



// getPassword - Prompt for password. Use stty to disable echoing.
import ( "bufio"; "fmt"; "os"; "strings"; "syscall" )
func getPassword(prompt string) string
fmt.Print(prompt)

// Common settings and variables for both stty calls.
attrs := syscall.ProcAttr
Dir: "",
Env: string,
Files: uintptros.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(),
Sys: nil
var ws syscall.WaitStatus

// Disable echoing.
pid, err := syscall.ForkExec(
"/bin/stty",
string"stty", "-echo",
&attrs)
if err != nil
panic(err)


// Wait for the stty process to complete.
_, err = syscall.Wait4(pid, &ws, 0, nil)
if err != nil
panic(err)


// Echo is disabled, now grab the data.
reader := bufio.NewReader(os.Stdin)
text, err := reader.ReadString('n')
if err != nil
panic(err)


// Re-enable echo.
pid, err = syscall.ForkExec(
"/bin/stty",
string"stty", "echo",
&attrs)
if err != nil
panic(err)


// Wait for the stty process to complete.
_, err = syscall.Wait4(pid, &ws, 0, nil)
if err != nil
panic(err)


return strings.TrimSpace(text)






share|improve this answer






















  • Just tried the code. It works well on go 1.10.3 amd64.
    – minghua
    Aug 31 at 20:50

















up vote
1
down vote













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("nnPassword: '%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.Fileos.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:nt%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:nt%s",e))

return passwd, err






share|improve this answer




















  • The code does not build with go 1.10.3. Among the errors, the undefined os.Error can be fixed by changing os.Error to error, similar to github.com/imbc/go_starter_package/issues/1. There seems to have lots of golang changes. Though thanks for sharing.
    – minghua
    Aug 31 at 21:34


















up vote
1
down vote













You could also use PasswordPrompt function of https://github.com/peterh/liner package.






share|improve this answer



























    up vote
    0
    down vote













    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.






    share|improve this answer



























      up vote
      -3
      down vote













      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.






      share|improve this answer




















      • This is platform independent, handled by application! Any reason why something like gopass has been written instead of this above snippet?
        – Sandeep Raju Prabhakar
        Jan 26 '14 at 9:50






      • 3




        The key difference here is that os.Stdin.Read still echo's the characters to the command prompt which is what the question was trying to avoid.
        – Nucleon
        May 7 '14 at 16:58










      • The assertion that this program won't echo until the Printf() call is incorrect. On Darwin, I see two copies of the inputted string: one when I type it, and one when I hit enter.
        – Alaska
        Sep 17 '15 at 21:03










      • Just tried this code on ubuntu amd64 and arm64. It echos when I'm typing, on both platforms. Though thanks for sharing the idea.
        – minghua
        Aug 31 at 21:23










      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2137357%2fgetpasswd-functionality-in-go%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      9 Answers
      9






      active

      oldest

      votes








      9 Answers
      9






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      7
      down vote



      accepted










      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






      share|improve this answer


















      • 1




        Thanks for this clue to use stty (am more familiar with Windows than *nix). Note in the source code solution I provide, I needed to specificaly use Go's ForkExec() call. The ordinary Exec() call replaces the current process with stty process.
        – RogerV
        Jan 26 '10 at 8:23






      • 1




        The Go ForkExec() call is now in syscall package and takes two fewer arguments.
        – RogerV
        Jul 17 '11 at 4:16














      up vote
      7
      down vote



      accepted










      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






      share|improve this answer


















      • 1




        Thanks for this clue to use stty (am more familiar with Windows than *nix). Note in the source code solution I provide, I needed to specificaly use Go's ForkExec() call. The ordinary Exec() call replaces the current process with stty process.
        – RogerV
        Jan 26 '10 at 8:23






      • 1




        The Go ForkExec() call is now in syscall package and takes two fewer arguments.
        – RogerV
        Jul 17 '11 at 4:16












      up vote
      7
      down vote



      accepted







      up vote
      7
      down vote



      accepted






      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






      share|improve this answer














      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







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jan 26 '10 at 5:26

























      answered Jan 26 '10 at 3:37









      jspcal

      37.8k45059




      37.8k45059







      • 1




        Thanks for this clue to use stty (am more familiar with Windows than *nix). Note in the source code solution I provide, I needed to specificaly use Go's ForkExec() call. The ordinary Exec() call replaces the current process with stty process.
        – RogerV
        Jan 26 '10 at 8:23






      • 1




        The Go ForkExec() call is now in syscall package and takes two fewer arguments.
        – RogerV
        Jul 17 '11 at 4:16












      • 1




        Thanks for this clue to use stty (am more familiar with Windows than *nix). Note in the source code solution I provide, I needed to specificaly use Go's ForkExec() call. The ordinary Exec() call replaces the current process with stty process.
        – RogerV
        Jan 26 '10 at 8:23






      • 1




        The Go ForkExec() call is now in syscall package and takes two fewer arguments.
        – RogerV
        Jul 17 '11 at 4:16







      1




      1




      Thanks for this clue to use stty (am more familiar with Windows than *nix). Note in the source code solution I provide, I needed to specificaly use Go's ForkExec() call. The ordinary Exec() call replaces the current process with stty process.
      – RogerV
      Jan 26 '10 at 8:23




      Thanks for this clue to use stty (am more familiar with Windows than *nix). Note in the source code solution I provide, I needed to specificaly use Go's ForkExec() call. The ordinary Exec() call replaces the current process with stty process.
      – RogerV
      Jan 26 '10 at 8:23




      1




      1




      The Go ForkExec() call is now in syscall package and takes two fewer arguments.
      – RogerV
      Jul 17 '11 at 4:16




      The Go ForkExec() call is now in syscall package and takes two fewer arguments.
      – RogerV
      Jul 17 '11 at 4:16












      up vote
      59
      down vote













      The following is one of best ways to get it done.
      First get terminal package by go get golang.org/x/crypto/ssh



      package main

      import (
      "bufio"
      "fmt"
      "os"
      "strings"
      "syscall"

      "golang.org/x/crypto/ssh/terminal"
      )

      func main()
      username, password := credentials()
      fmt.Printf("Username: %s, Password: %sn", username, password)


      func credentials() (string, string)
      reader := bufio.NewReader(os.Stdin)

      fmt.Print("Enter Username: ")
      username, _ := reader.ReadString('n')

      fmt.Print("Enter Password: ")
      bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
      if err == nil
      fmt.Println("nPassword typed: " + string(bytePassword))

      password := string(bytePassword)

      return strings.TrimSpace(username), strings.TrimSpace(password)



      http://play.golang.org/p/l-9IP1mrhA






      share|improve this answer






















      • This should work on windows? I'm keep getting "panic: The handle is invalid" for this.
        – Shikloshi
        Oct 20 '15 at 13:43










      • @Shikloshi I tried this on Ubunut with go version go1.5.1 linux/amd64, and it's working perfectly. Also I think it should work on Windows as well, but didn't check. You can't run it on play golang since we can't install custom packages.
        – gihanchanuka
        Oct 20 '15 at 13:58






      • 9




        It didn't work because of the wrong assumption that 0 is stdin handler in windows (which is not), you can make this code work cross-platform by using terminal.ReadPassword(int(syscall.Stdin)) instead of 0. Thanks a lot, for my opinion the best implementation.
        – Shikloshi
        Oct 20 '15 at 14:47











      • Does this handle UTF8?
        – Ztyx
        Feb 16 '16 at 21:48






      • 3




        you may not want to trim space from password?
        – Senthil Kumar
        Feb 16 at 8:53














      up vote
      59
      down vote













      The following is one of best ways to get it done.
      First get terminal package by go get golang.org/x/crypto/ssh



      package main

      import (
      "bufio"
      "fmt"
      "os"
      "strings"
      "syscall"

      "golang.org/x/crypto/ssh/terminal"
      )

      func main()
      username, password := credentials()
      fmt.Printf("Username: %s, Password: %sn", username, password)


      func credentials() (string, string)
      reader := bufio.NewReader(os.Stdin)

      fmt.Print("Enter Username: ")
      username, _ := reader.ReadString('n')

      fmt.Print("Enter Password: ")
      bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
      if err == nil
      fmt.Println("nPassword typed: " + string(bytePassword))

      password := string(bytePassword)

      return strings.TrimSpace(username), strings.TrimSpace(password)



      http://play.golang.org/p/l-9IP1mrhA






      share|improve this answer






















      • This should work on windows? I'm keep getting "panic: The handle is invalid" for this.
        – Shikloshi
        Oct 20 '15 at 13:43










      • @Shikloshi I tried this on Ubunut with go version go1.5.1 linux/amd64, and it's working perfectly. Also I think it should work on Windows as well, but didn't check. You can't run it on play golang since we can't install custom packages.
        – gihanchanuka
        Oct 20 '15 at 13:58






      • 9




        It didn't work because of the wrong assumption that 0 is stdin handler in windows (which is not), you can make this code work cross-platform by using terminal.ReadPassword(int(syscall.Stdin)) instead of 0. Thanks a lot, for my opinion the best implementation.
        – Shikloshi
        Oct 20 '15 at 14:47











      • Does this handle UTF8?
        – Ztyx
        Feb 16 '16 at 21:48






      • 3




        you may not want to trim space from password?
        – Senthil Kumar
        Feb 16 at 8:53












      up vote
      59
      down vote










      up vote
      59
      down vote









      The following is one of best ways to get it done.
      First get terminal package by go get golang.org/x/crypto/ssh



      package main

      import (
      "bufio"
      "fmt"
      "os"
      "strings"
      "syscall"

      "golang.org/x/crypto/ssh/terminal"
      )

      func main()
      username, password := credentials()
      fmt.Printf("Username: %s, Password: %sn", username, password)


      func credentials() (string, string)
      reader := bufio.NewReader(os.Stdin)

      fmt.Print("Enter Username: ")
      username, _ := reader.ReadString('n')

      fmt.Print("Enter Password: ")
      bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
      if err == nil
      fmt.Println("nPassword typed: " + string(bytePassword))

      password := string(bytePassword)

      return strings.TrimSpace(username), strings.TrimSpace(password)



      http://play.golang.org/p/l-9IP1mrhA






      share|improve this answer














      The following is one of best ways to get it done.
      First get terminal package by go get golang.org/x/crypto/ssh



      package main

      import (
      "bufio"
      "fmt"
      "os"
      "strings"
      "syscall"

      "golang.org/x/crypto/ssh/terminal"
      )

      func main()
      username, password := credentials()
      fmt.Printf("Username: %s, Password: %sn", username, password)


      func credentials() (string, string)
      reader := bufio.NewReader(os.Stdin)

      fmt.Print("Enter Username: ")
      username, _ := reader.ReadString('n')

      fmt.Print("Enter Password: ")
      bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
      if err == nil
      fmt.Println("nPassword typed: " + string(bytePassword))

      password := string(bytePassword)

      return strings.TrimSpace(username), strings.TrimSpace(password)



      http://play.golang.org/p/l-9IP1mrhA







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 7 '16 at 11:31









      atomsymbol

      13438




      13438










      answered Sep 24 '15 at 18:31









      gihanchanuka

      1,6531521




      1,6531521











      • This should work on windows? I'm keep getting "panic: The handle is invalid" for this.
        – Shikloshi
        Oct 20 '15 at 13:43










      • @Shikloshi I tried this on Ubunut with go version go1.5.1 linux/amd64, and it's working perfectly. Also I think it should work on Windows as well, but didn't check. You can't run it on play golang since we can't install custom packages.
        – gihanchanuka
        Oct 20 '15 at 13:58






      • 9




        It didn't work because of the wrong assumption that 0 is stdin handler in windows (which is not), you can make this code work cross-platform by using terminal.ReadPassword(int(syscall.Stdin)) instead of 0. Thanks a lot, for my opinion the best implementation.
        – Shikloshi
        Oct 20 '15 at 14:47











      • Does this handle UTF8?
        – Ztyx
        Feb 16 '16 at 21:48






      • 3




        you may not want to trim space from password?
        – Senthil Kumar
        Feb 16 at 8:53
















      • This should work on windows? I'm keep getting "panic: The handle is invalid" for this.
        – Shikloshi
        Oct 20 '15 at 13:43










      • @Shikloshi I tried this on Ubunut with go version go1.5.1 linux/amd64, and it's working perfectly. Also I think it should work on Windows as well, but didn't check. You can't run it on play golang since we can't install custom packages.
        – gihanchanuka
        Oct 20 '15 at 13:58






      • 9




        It didn't work because of the wrong assumption that 0 is stdin handler in windows (which is not), you can make this code work cross-platform by using terminal.ReadPassword(int(syscall.Stdin)) instead of 0. Thanks a lot, for my opinion the best implementation.
        – Shikloshi
        Oct 20 '15 at 14:47











      • Does this handle UTF8?
        – Ztyx
        Feb 16 '16 at 21:48






      • 3




        you may not want to trim space from password?
        – Senthil Kumar
        Feb 16 at 8:53















      This should work on windows? I'm keep getting "panic: The handle is invalid" for this.
      – Shikloshi
      Oct 20 '15 at 13:43




      This should work on windows? I'm keep getting "panic: The handle is invalid" for this.
      – Shikloshi
      Oct 20 '15 at 13:43












      @Shikloshi I tried this on Ubunut with go version go1.5.1 linux/amd64, and it's working perfectly. Also I think it should work on Windows as well, but didn't check. You can't run it on play golang since we can't install custom packages.
      – gihanchanuka
      Oct 20 '15 at 13:58




      @Shikloshi I tried this on Ubunut with go version go1.5.1 linux/amd64, and it's working perfectly. Also I think it should work on Windows as well, but didn't check. You can't run it on play golang since we can't install custom packages.
      – gihanchanuka
      Oct 20 '15 at 13:58




      9




      9




      It didn't work because of the wrong assumption that 0 is stdin handler in windows (which is not), you can make this code work cross-platform by using terminal.ReadPassword(int(syscall.Stdin)) instead of 0. Thanks a lot, for my opinion the best implementation.
      – Shikloshi
      Oct 20 '15 at 14:47





      It didn't work because of the wrong assumption that 0 is stdin handler in windows (which is not), you can make this code work cross-platform by using terminal.ReadPassword(int(syscall.Stdin)) instead of 0. Thanks a lot, for my opinion the best implementation.
      – Shikloshi
      Oct 20 '15 at 14:47













      Does this handle UTF8?
      – Ztyx
      Feb 16 '16 at 21:48




      Does this handle UTF8?
      – Ztyx
      Feb 16 '16 at 21:48




      3




      3




      you may not want to trim space from password?
      – Senthil Kumar
      Feb 16 at 8:53




      you may not want to trim space from password?
      – Senthil Kumar
      Feb 16 at 8:53










      up vote
      27
      down vote













      Just saw a mail in #go-nuts maillist. There is someone who wrote quite a simple go package to be used. You can find it here: https://github.com/howeyc/gopass



      It something like that:



      package main

      import "fmt"
      import "github.com/howeyc/gopass"

      func main()
      fmt.Printf("Password: ")
      pass := gopass.GetPasswd()
      // Do something with pass






      share|improve this answer
















      • 7




        Note, this package uses terminal.MakeRaw from the Go Author's golang.org/x/crypto/ssh/terminal package. That can be used directly if desired.
        – Dave C
        Jul 23 '15 at 14:08






      • 8




        Oh, and there is also terminal.ReadPassword.
        – Dave C
        Jul 23 '15 at 14:14










      • Yeah, that package is a bit silly.
        – Tincho
        May 3 '16 at 19:24














      up vote
      27
      down vote













      Just saw a mail in #go-nuts maillist. There is someone who wrote quite a simple go package to be used. You can find it here: https://github.com/howeyc/gopass



      It something like that:



      package main

      import "fmt"
      import "github.com/howeyc/gopass"

      func main()
      fmt.Printf("Password: ")
      pass := gopass.GetPasswd()
      // Do something with pass






      share|improve this answer
















      • 7




        Note, this package uses terminal.MakeRaw from the Go Author's golang.org/x/crypto/ssh/terminal package. That can be used directly if desired.
        – Dave C
        Jul 23 '15 at 14:08






      • 8




        Oh, and there is also terminal.ReadPassword.
        – Dave C
        Jul 23 '15 at 14:14










      • Yeah, that package is a bit silly.
        – Tincho
        May 3 '16 at 19:24












      up vote
      27
      down vote










      up vote
      27
      down vote









      Just saw a mail in #go-nuts maillist. There is someone who wrote quite a simple go package to be used. You can find it here: https://github.com/howeyc/gopass



      It something like that:



      package main

      import "fmt"
      import "github.com/howeyc/gopass"

      func main()
      fmt.Printf("Password: ")
      pass := gopass.GetPasswd()
      // Do something with pass






      share|improve this answer












      Just saw a mail in #go-nuts maillist. There is someone who wrote quite a simple go package to be used. You can find it here: https://github.com/howeyc/gopass



      It something like that:



      package main

      import "fmt"
      import "github.com/howeyc/gopass"

      func main()
      fmt.Printf("Password: ")
      pass := gopass.GetPasswd()
      // Do something with pass







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 15 '12 at 8:07









      Fatih Arslan

      8,73474349




      8,73474349







      • 7




        Note, this package uses terminal.MakeRaw from the Go Author's golang.org/x/crypto/ssh/terminal package. That can be used directly if desired.
        – Dave C
        Jul 23 '15 at 14:08






      • 8




        Oh, and there is also terminal.ReadPassword.
        – Dave C
        Jul 23 '15 at 14:14










      • Yeah, that package is a bit silly.
        – Tincho
        May 3 '16 at 19:24












      • 7




        Note, this package uses terminal.MakeRaw from the Go Author's golang.org/x/crypto/ssh/terminal package. That can be used directly if desired.
        – Dave C
        Jul 23 '15 at 14:08






      • 8




        Oh, and there is also terminal.ReadPassword.
        – Dave C
        Jul 23 '15 at 14:14










      • Yeah, that package is a bit silly.
        – Tincho
        May 3 '16 at 19:24







      7




      7




      Note, this package uses terminal.MakeRaw from the Go Author's golang.org/x/crypto/ssh/terminal package. That can be used directly if desired.
      – Dave C
      Jul 23 '15 at 14:08




      Note, this package uses terminal.MakeRaw from the Go Author's golang.org/x/crypto/ssh/terminal package. That can be used directly if desired.
      – Dave C
      Jul 23 '15 at 14:08




      8




      8




      Oh, and there is also terminal.ReadPassword.
      – Dave C
      Jul 23 '15 at 14:14




      Oh, and there is also terminal.ReadPassword.
      – Dave C
      Jul 23 '15 at 14:14












      Yeah, that package is a bit silly.
      – Tincho
      May 3 '16 at 19:24




      Yeah, that package is a bit silly.
      – Tincho
      May 3 '16 at 19:24










      up vote
      2
      down vote













      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 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.






      share|improve this answer






















      • The Go Author's golang.org/x/crypto/ssh/terminal package does this exact thing but handles all the OSes supported by Go. (E.g. by using syscall.TIOCSETA instead of syscall.TCSETS for BSD and using kernel32.dll on Windows).
        – Dave C
        Jul 23 '15 at 14:12














      up vote
      2
      down vote













      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 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.






      share|improve this answer






















      • The Go Author's golang.org/x/crypto/ssh/terminal package does this exact thing but handles all the OSes supported by Go. (E.g. by using syscall.TIOCSETA instead of syscall.TCSETS for BSD and using kernel32.dll on Windows).
        – Dave C
        Jul 23 '15 at 14:12












      up vote
      2
      down vote










      up vote
      2
      down vote









      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 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.






      share|improve this answer














      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 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.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 2 '16 at 17:36







      user6169399

















      answered Jul 22 '15 at 19:11









      Colin Fox

      383




      383











      • The Go Author's golang.org/x/crypto/ssh/terminal package does this exact thing but handles all the OSes supported by Go. (E.g. by using syscall.TIOCSETA instead of syscall.TCSETS for BSD and using kernel32.dll on Windows).
        – Dave C
        Jul 23 '15 at 14:12
















      • The Go Author's golang.org/x/crypto/ssh/terminal package does this exact thing but handles all the OSes supported by Go. (E.g. by using syscall.TIOCSETA instead of syscall.TCSETS for BSD and using kernel32.dll on Windows).
        – Dave C
        Jul 23 '15 at 14:12















      The Go Author's golang.org/x/crypto/ssh/terminal package does this exact thing but handles all the OSes supported by Go. (E.g. by using syscall.TIOCSETA instead of syscall.TCSETS for BSD and using kernel32.dll on Windows).
      – Dave C
      Jul 23 '15 at 14:12




      The Go Author's golang.org/x/crypto/ssh/terminal package does this exact thing but handles all the OSes supported by Go. (E.g. by using syscall.TIOCSETA instead of syscall.TCSETS for BSD and using kernel32.dll on Windows).
      – Dave C
      Jul 23 '15 at 14:12










      up vote
      2
      down vote













      Here is a solution that I developed using Go1.6.2 that you might find useful.



      It only uses the following standard packages: bufio, fmt, os, strings and syscall. More specifically, it uses syscall.ForkExec() and syscall.Wait4() to invoke stty to disable/enable terminal echo.



      I have tested it on Linux and BSD (Mac). It will not work on windows.



      // getPassword - Prompt for password. Use stty to disable echoing.
      import ( "bufio"; "fmt"; "os"; "strings"; "syscall" )
      func getPassword(prompt string) string
      fmt.Print(prompt)

      // Common settings and variables for both stty calls.
      attrs := syscall.ProcAttr
      Dir: "",
      Env: string,
      Files: uintptros.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(),
      Sys: nil
      var ws syscall.WaitStatus

      // Disable echoing.
      pid, err := syscall.ForkExec(
      "/bin/stty",
      string"stty", "-echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      // Echo is disabled, now grab the data.
      reader := bufio.NewReader(os.Stdin)
      text, err := reader.ReadString('n')
      if err != nil
      panic(err)


      // Re-enable echo.
      pid, err = syscall.ForkExec(
      "/bin/stty",
      string"stty", "echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      return strings.TrimSpace(text)






      share|improve this answer






















      • Just tried the code. It works well on go 1.10.3 amd64.
        – minghua
        Aug 31 at 20:50














      up vote
      2
      down vote













      Here is a solution that I developed using Go1.6.2 that you might find useful.



      It only uses the following standard packages: bufio, fmt, os, strings and syscall. More specifically, it uses syscall.ForkExec() and syscall.Wait4() to invoke stty to disable/enable terminal echo.



      I have tested it on Linux and BSD (Mac). It will not work on windows.



      // getPassword - Prompt for password. Use stty to disable echoing.
      import ( "bufio"; "fmt"; "os"; "strings"; "syscall" )
      func getPassword(prompt string) string
      fmt.Print(prompt)

      // Common settings and variables for both stty calls.
      attrs := syscall.ProcAttr
      Dir: "",
      Env: string,
      Files: uintptros.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(),
      Sys: nil
      var ws syscall.WaitStatus

      // Disable echoing.
      pid, err := syscall.ForkExec(
      "/bin/stty",
      string"stty", "-echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      // Echo is disabled, now grab the data.
      reader := bufio.NewReader(os.Stdin)
      text, err := reader.ReadString('n')
      if err != nil
      panic(err)


      // Re-enable echo.
      pid, err = syscall.ForkExec(
      "/bin/stty",
      string"stty", "echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      return strings.TrimSpace(text)






      share|improve this answer






















      • Just tried the code. It works well on go 1.10.3 amd64.
        – minghua
        Aug 31 at 20:50












      up vote
      2
      down vote










      up vote
      2
      down vote









      Here is a solution that I developed using Go1.6.2 that you might find useful.



      It only uses the following standard packages: bufio, fmt, os, strings and syscall. More specifically, it uses syscall.ForkExec() and syscall.Wait4() to invoke stty to disable/enable terminal echo.



      I have tested it on Linux and BSD (Mac). It will not work on windows.



      // getPassword - Prompt for password. Use stty to disable echoing.
      import ( "bufio"; "fmt"; "os"; "strings"; "syscall" )
      func getPassword(prompt string) string
      fmt.Print(prompt)

      // Common settings and variables for both stty calls.
      attrs := syscall.ProcAttr
      Dir: "",
      Env: string,
      Files: uintptros.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(),
      Sys: nil
      var ws syscall.WaitStatus

      // Disable echoing.
      pid, err := syscall.ForkExec(
      "/bin/stty",
      string"stty", "-echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      // Echo is disabled, now grab the data.
      reader := bufio.NewReader(os.Stdin)
      text, err := reader.ReadString('n')
      if err != nil
      panic(err)


      // Re-enable echo.
      pid, err = syscall.ForkExec(
      "/bin/stty",
      string"stty", "echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      return strings.TrimSpace(text)






      share|improve this answer














      Here is a solution that I developed using Go1.6.2 that you might find useful.



      It only uses the following standard packages: bufio, fmt, os, strings and syscall. More specifically, it uses syscall.ForkExec() and syscall.Wait4() to invoke stty to disable/enable terminal echo.



      I have tested it on Linux and BSD (Mac). It will not work on windows.



      // getPassword - Prompt for password. Use stty to disable echoing.
      import ( "bufio"; "fmt"; "os"; "strings"; "syscall" )
      func getPassword(prompt string) string
      fmt.Print(prompt)

      // Common settings and variables for both stty calls.
      attrs := syscall.ProcAttr
      Dir: "",
      Env: string,
      Files: uintptros.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd(),
      Sys: nil
      var ws syscall.WaitStatus

      // Disable echoing.
      pid, err := syscall.ForkExec(
      "/bin/stty",
      string"stty", "-echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      // Echo is disabled, now grab the data.
      reader := bufio.NewReader(os.Stdin)
      text, err := reader.ReadString('n')
      if err != nil
      panic(err)


      // Re-enable echo.
      pid, err = syscall.ForkExec(
      "/bin/stty",
      string"stty", "echo",
      &attrs)
      if err != nil
      panic(err)


      // Wait for the stty process to complete.
      _, err = syscall.Wait4(pid, &ws, 0, nil)
      if err != nil
      panic(err)


      return strings.TrimSpace(text)







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Aug 31 at 20:49









      minghua

      2,21411943




      2,21411943










      answered May 7 '16 at 17:23









      Joe Linoff

      34426




      34426











      • Just tried the code. It works well on go 1.10.3 amd64.
        – minghua
        Aug 31 at 20:50
















      • Just tried the code. It works well on go 1.10.3 amd64.
        – minghua
        Aug 31 at 20:50















      Just tried the code. It works well on go 1.10.3 amd64.
      – minghua
      Aug 31 at 20:50




      Just tried the code. It works well on go 1.10.3 amd64.
      – minghua
      Aug 31 at 20:50










      up vote
      1
      down vote













      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("nnPassword: '%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.Fileos.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:nt%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:nt%s",e))

      return passwd, err






      share|improve this answer




















      • The code does not build with go 1.10.3. Among the errors, the undefined os.Error can be fixed by changing os.Error to error, similar to github.com/imbc/go_starter_package/issues/1. There seems to have lots of golang changes. Though thanks for sharing.
        – minghua
        Aug 31 at 21:34















      up vote
      1
      down vote













      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("nnPassword: '%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.Fileos.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:nt%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:nt%s",e))

      return passwd, err






      share|improve this answer




















      • The code does not build with go 1.10.3. Among the errors, the undefined os.Error can be fixed by changing os.Error to error, similar to github.com/imbc/go_starter_package/issues/1. There seems to have lots of golang changes. Though thanks for sharing.
        – minghua
        Aug 31 at 21:34













      up vote
      1
      down vote










      up vote
      1
      down vote









      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("nnPassword: '%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.Fileos.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:nt%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:nt%s",e))

      return passwd, err






      share|improve this answer












      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("nnPassword: '%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.Fileos.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:nt%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:nt%s",e))

      return passwd, err







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 26 '10 at 8:16









      RogerV

      2,40342132




      2,40342132











      • The code does not build with go 1.10.3. Among the errors, the undefined os.Error can be fixed by changing os.Error to error, similar to github.com/imbc/go_starter_package/issues/1. There seems to have lots of golang changes. Though thanks for sharing.
        – minghua
        Aug 31 at 21:34

















      • The code does not build with go 1.10.3. Among the errors, the undefined os.Error can be fixed by changing os.Error to error, similar to github.com/imbc/go_starter_package/issues/1. There seems to have lots of golang changes. Though thanks for sharing.
        – minghua
        Aug 31 at 21:34
















      The code does not build with go 1.10.3. Among the errors, the undefined os.Error can be fixed by changing os.Error to error, similar to github.com/imbc/go_starter_package/issues/1. There seems to have lots of golang changes. Though thanks for sharing.
      – minghua
      Aug 31 at 21:34





      The code does not build with go 1.10.3. Among the errors, the undefined os.Error can be fixed by changing os.Error to error, similar to github.com/imbc/go_starter_package/issues/1. There seems to have lots of golang changes. Though thanks for sharing.
      – minghua
      Aug 31 at 21:34











      up vote
      1
      down vote













      You could also use PasswordPrompt function of https://github.com/peterh/liner package.






      share|improve this answer
























        up vote
        1
        down vote













        You could also use PasswordPrompt function of https://github.com/peterh/liner package.






        share|improve this answer






















          up vote
          1
          down vote










          up vote
          1
          down vote









          You could also use PasswordPrompt function of https://github.com/peterh/liner package.






          share|improve this answer












          You could also use PasswordPrompt function of https://github.com/peterh/liner package.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered May 6 '16 at 23:38









          hagh

          128110




          128110




















              up vote
              0
              down vote













              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.






              share|improve this answer
























                up vote
                0
                down vote













                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.






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  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.






                  share|improve this answer












                  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.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 26 at 1:45









                  rjni

                  17625




                  17625




















                      up vote
                      -3
                      down vote













                      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.






                      share|improve this answer




















                      • This is platform independent, handled by application! Any reason why something like gopass has been written instead of this above snippet?
                        – Sandeep Raju Prabhakar
                        Jan 26 '14 at 9:50






                      • 3




                        The key difference here is that os.Stdin.Read still echo's the characters to the command prompt which is what the question was trying to avoid.
                        – Nucleon
                        May 7 '14 at 16:58










                      • The assertion that this program won't echo until the Printf() call is incorrect. On Darwin, I see two copies of the inputted string: one when I type it, and one when I hit enter.
                        – Alaska
                        Sep 17 '15 at 21:03










                      • Just tried this code on ubuntu amd64 and arm64. It echos when I'm typing, on both platforms. Though thanks for sharing the idea.
                        – minghua
                        Aug 31 at 21:23














                      up vote
                      -3
                      down vote













                      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.






                      share|improve this answer




















                      • This is platform independent, handled by application! Any reason why something like gopass has been written instead of this above snippet?
                        – Sandeep Raju Prabhakar
                        Jan 26 '14 at 9:50






                      • 3




                        The key difference here is that os.Stdin.Read still echo's the characters to the command prompt which is what the question was trying to avoid.
                        – Nucleon
                        May 7 '14 at 16:58










                      • The assertion that this program won't echo until the Printf() call is incorrect. On Darwin, I see two copies of the inputted string: one when I type it, and one when I hit enter.
                        – Alaska
                        Sep 17 '15 at 21:03










                      • Just tried this code on ubuntu amd64 and arm64. It echos when I'm typing, on both platforms. Though thanks for sharing the idea.
                        – minghua
                        Aug 31 at 21:23












                      up vote
                      -3
                      down vote










                      up vote
                      -3
                      down vote









                      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.






                      share|improve this answer












                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 26 '10 at 5:01









                      Russell Newquist

                      2,47821117




                      2,47821117











                      • This is platform independent, handled by application! Any reason why something like gopass has been written instead of this above snippet?
                        – Sandeep Raju Prabhakar
                        Jan 26 '14 at 9:50






                      • 3




                        The key difference here is that os.Stdin.Read still echo's the characters to the command prompt which is what the question was trying to avoid.
                        – Nucleon
                        May 7 '14 at 16:58










                      • The assertion that this program won't echo until the Printf() call is incorrect. On Darwin, I see two copies of the inputted string: one when I type it, and one when I hit enter.
                        – Alaska
                        Sep 17 '15 at 21:03










                      • Just tried this code on ubuntu amd64 and arm64. It echos when I'm typing, on both platforms. Though thanks for sharing the idea.
                        – minghua
                        Aug 31 at 21:23
















                      • This is platform independent, handled by application! Any reason why something like gopass has been written instead of this above snippet?
                        – Sandeep Raju Prabhakar
                        Jan 26 '14 at 9:50






                      • 3




                        The key difference here is that os.Stdin.Read still echo's the characters to the command prompt which is what the question was trying to avoid.
                        – Nucleon
                        May 7 '14 at 16:58










                      • The assertion that this program won't echo until the Printf() call is incorrect. On Darwin, I see two copies of the inputted string: one when I type it, and one when I hit enter.
                        – Alaska
                        Sep 17 '15 at 21:03










                      • Just tried this code on ubuntu amd64 and arm64. It echos when I'm typing, on both platforms. Though thanks for sharing the idea.
                        – minghua
                        Aug 31 at 21:23















                      This is platform independent, handled by application! Any reason why something like gopass has been written instead of this above snippet?
                      – Sandeep Raju Prabhakar
                      Jan 26 '14 at 9:50




                      This is platform independent, handled by application! Any reason why something like gopass has been written instead of this above snippet?
                      – Sandeep Raju Prabhakar
                      Jan 26 '14 at 9:50




                      3




                      3




                      The key difference here is that os.Stdin.Read still echo's the characters to the command prompt which is what the question was trying to avoid.
                      – Nucleon
                      May 7 '14 at 16:58




                      The key difference here is that os.Stdin.Read still echo's the characters to the command prompt which is what the question was trying to avoid.
                      – Nucleon
                      May 7 '14 at 16:58












                      The assertion that this program won't echo until the Printf() call is incorrect. On Darwin, I see two copies of the inputted string: one when I type it, and one when I hit enter.
                      – Alaska
                      Sep 17 '15 at 21:03




                      The assertion that this program won't echo until the Printf() call is incorrect. On Darwin, I see two copies of the inputted string: one when I type it, and one when I hit enter.
                      – Alaska
                      Sep 17 '15 at 21:03












                      Just tried this code on ubuntu amd64 and arm64. It echos when I'm typing, on both platforms. Though thanks for sharing the idea.
                      – minghua
                      Aug 31 at 21:23




                      Just tried this code on ubuntu amd64 and arm64. It echos when I'm typing, on both platforms. Though thanks for sharing the idea.
                      – minghua
                      Aug 31 at 21:23

















                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2137357%2fgetpasswd-functionality-in-go%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                      ReactJS Fetched API data displays live - need Data displayed static

                      Evgeni Malkin