Go – 写入外部命令的标准输入(stdin)。

huangapple go评论77阅读模式
英文:

Go - write to stdin on external command

问题

我有以下代码,它执行一个外部命令并将输出打印到控制台,等待用户输入两个字段。一个用于用户名,另一个用于密码,然后我手动添加它们。

有人可以给我一个提示,如何在程序内部写入stdin以输入这些输入?

对我来说棘手的部分是有两个不同的字段等待输入,我不知道如何依次填充它们。

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
英文:

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 added them manually.

Could anyone give me a hint about how to write to stdin in order to enter these inputs from inside the program?

The tricky part for me is that 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)
}

SOLUTION:

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

答案1

得分: 9

我想你可以使用bytes.Buffer来实现这个功能。类似这样:

login := exec.Command(cmd, "login")

buffer := bytes.Buffer{}
buffer.Write([]byte("username\npassword\n"))
login.Stdin = &buffer

login.Stdout = os.Stdout
login.Stderr = os.Stderr

err := login.Run()
if err != nil {
    fmt.Fprintln(os.Stderr, err)
}

关键在于stdin只是一个字符缓冲区,当读取凭据时,它会简单地读取字符,直到遇到\n字符(或者可能是\n\r)。因此,你可以预先将它们写入缓冲区,并直接将缓冲区提供给命令。

英文:

I imagine you could use a bytes.Buffer for that.
Something like that:

login := exec.Command(cmd, "login")

buffer := bytes.Buffer{}
buffer.Write([]byte("username\npassword\n"))
login.Stdin = &buffer

login.Stdout = os.Stdout
login.Stderr = os.Stderr

err := login.Run()
if err != nil {
    fmt.Fprintln(os.Stderr, err)
}

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.

huangapple
  • 本文由 发表于 2016年4月3日 15:46:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/36382880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定