去 - 写入外部命令的stdin [英] Go - write to stdin on external command
问题描述
我有以下代码执行外部命令并输出到控制台的两个等待用户输入的字段。
一个用于用户名和其他密码,然后我手动添加它们。
I have the following code which executes an external command and output to the console two fields waiting for the user input. One for the username and other for the password, and then I have add them manually.
任何人都可以给我一个关于如何写入stdin的提示为了从程序内部输入这些输入?
Could anyone give me a hint about how to write to stdin in order to enter these inputs from inside the program?
对我来说,诀窍是有两个不同的领域等待输入,而我很难找出如何填充一个接一个。
The trick part for me is there are two different fields waiting for input, and I'm having trouble to figure out how to fill one after the other.
login := exec.Command(cmd, "login")
login.Stdout = os.Stdout
login.Stdin = os.Stdin
login.Stderr = os.Stderr
err := login.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
解决方案:
login := exec.Command(cmd, "login)
var b bytes.Buffer
b.Write([]byte(username + "\n" + pwd + "\n"))
login.Stdout = os.Stdout
login.Stdin = &b
login.Stderr = os.Stderr
推荐答案
我想你可以使用一个 bytes.Buffer
作为那个。
类似的东西(未测试):
I imagine you could use a bytes.Buffer
for that.
Something like that (not tested):
login := exec.Command(cmd, "login")
buffer := bytes.Buffer{}
buffer.Write([]bytes("username\npassword\n")
login.Stdout = os.Stdout
login.Stdin = buffer
login.Stderr = os.Stderr
err := login.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
关键在于stdin只是一个char缓冲区,当读取凭证时,它只会读取字符,直到遇到 \\\
字符(或者
\\\
)。所以你可以预先将它们写入缓冲区,然后直接将缓冲区提供给命令...
\r
The trick is that the stdin is merely a char buffer, and when reading the credentials, it will simply read chars until encountering a \n
character (or maybe \n\r
). So you can write them in a buffer in advance, and feed the buffer directly to the command…
这篇关于去 - 写入外部命令的stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!