Home > Software engineering >  input password to command in golang
input password to command in golang

Time:11-18

I need to use lxd-p2c(https://github.com/lxc/lxd/tree/master/lxd-p2c) in golang code.

I try to pass password to the binary lxd-p2c built by the code above, which uses term.ReadPassword(0)(https://github.com/lxc/lxd/blob/master/lxd-p2c/utils.go#L166) to read password in Linux.

I did some search on the internet and tried following code but they just did not work.

# 1
cmd := exec.Command(command, args...)
cmd.Stdin = strings.NewReader(password)

# 2
cmd := exec.Command(command, args...)
stdin, _ := cmd.StdinPipe()
io.WriteString(stdin, password)

Similar but simple code to test: https://play.golang.org/p/l-9IP1mrhA (code from https://stackoverflow.com/a/32768479/9265302)

build the binary and call it in go.


edit:

No workaround found and I removed term.ReadPassword(0) in the source code.

CodePudding user response:

Checking the error in your playground displays inappropriate ioctl for device.

Searching for the error message I found this thread [1], which notes that non-terminal input is not supported for terminal.ReadPassword. My guess is that passing Stdin input this way makes it pass the input with a character device instead of with the necessary terminal device like tty or any such, making the read fail. lxd-p2c can't read the password from such an input device.

  •  Tags:  
  • go
  • Related