英文:
input password to command in golang
问题
我需要在Go语言代码中使用lxd-p2c(https://github.com/lxc/lxd/tree/master/lxd-p2c)。
我尝试将密码传递给上述代码构建的二进制文件lxd-p2c
,该二进制文件使用term.ReadPassword(0)
(https://github.com/lxc/lxd/blob/master/lxd-p2c/utils.go#L166)在Linux中读取密码。
我在互联网上进行了一些搜索,并尝试了以下代码,但它们都没有起作用。
# 1
cmd := exec.Command(command, args...)
cmd.Stdin = strings.NewReader(password)
# 2
cmd := exec.Command(command, args...)
stdin, _ := cmd.StdinPipe()
io.WriteString(stdin, password)
类似但更简单的测试代码:https://play.golang.org/p/l-9IP1mrhA(代码来自https://stackoverflow.com/a/32768479/9265302)
构建该二进制文件并在Go中调用它。
编辑:
没有找到解决方法,我已经从源代码中删除了term.ReadPassword(0)
。
英文:
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.
答案1
得分: 1
在你的 playground 中检查错误时显示了 inappropriate ioctl for device
。
在搜索错误信息时,我找到了这个线程,它指出 terminal.ReadPassword
不支持非终端输入。我猜测以这种方式传递 Stdin 输入会使其通过字符设备而不是必要的终端设备(如 tty 或类似设备)进行输入,导致读取失败。lxd-p2c
无法从这样的输入设备中读取密码。
英文:
Checking the error in your playground displays inappropriate ioctl for device
.
Searching for the error message I found this thread, 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论