In Go, executing external commands and managing their input and outputs is a common task. However, when dealing with commands that prompt for user input, such as "login", it can be challenging to automate these inputs programmatically.
One approach to this problem is to write directly to the command's standard input (stdin) using a bytes buffer. Let's dive into the solution provided:
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
In this code, we create a bytes.Buffer named b and concatenate the username and password with newlines. We then assign b to the login command's Stdin field, effectively connecting the buffer to the command's input stream.
When the command executes, it will read characters from b until it encounters a newline, interpreting this as the username. It will then read until the next newline, treating this as the password. By manually writing to the buffer in this way, we bypass the need for user interaction and provide the necessary inputs programmatically.
Remember, stdin is a character buffer, and commands typically read input until they encounter newlines. This technique allows you to buffer and sequence inputs before feeding them to external commands, automating the input process without requiring manual user intervention.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3