第三个命令 RunCommand("mysql_secure_installation");
不显示 stdout/stderr 缓冲区,命令将不会完成。键盘输入有效,但不会影响该过程。
ssh 控制台上的 mysql_secure_installation
运行完美。
其他命令完美运行。
package main
import (
"fmt"
"os/exec"
"os"
"bufio"
)
func main() {
RunCommand("lsb_release -a"); //works perfect
RunCommand("apt-get update"); //works perfect
RunCommand("mysql_secure_installation"); //empty output and waiting for something!
}
func RunCommand(command string) {
args := []string {"-c", command}
executer := exec.Command("sh", args...)
stdout, err := executer.StdoutPipe()
if err != nil {
fmt.Print("Error creating STDOUT pipe")
os.Exit(1)
}
stderr, err := executer.StderrPipe()
if err != nil {
fmt.Print("Error creating STDERR pipe")
os.Exit(1)
}
stdoutScanner := bufio.NewScanner(stdout)
stdoutScanner.Split(bufio.ScanLines)
go func() {
for stdoutScanner.Scan() {
out := stdoutScanner.Text();
fmt.Printf("%s\n", out)
}
}()
stderrScanner := bufio.NewScanner(stderr)
stderrScanner.Split(bufio.ScanLines)
go func() {
for stderrScanner.Scan() {
error := stderrScanner.Text()
fmt.Printf("%s\n", error)
}
}()
err = executer.Start()
if err != nil {
os.Exit(1)
}
err = executer.Wait()
if err != nil {
os.Exit(1)
}
}
更新 1:
在此链接中发现并作为新问题提出的主要问题:How to store STDOUT buffer of `mysql_secure_installation` to a file
更新 2:
经过 CentOS 和 Debian 的测试,缓冲工作完美,但在我的目标操作系统 (Ubuntu 16.04 LTS) 上它不起作用。
最佳答案
它挂起的原因是它仍在等待用户输入完成。
如评论中所述,mysql_secure_installation
需要用户输入。如果您想在没有用户输入的情况下运行它,您可以尝试添加 --use-default
参数。
如果您想等待使用输入,请考虑阅读 Run
之间的区别和 Start
.来自文档:
Run starts the specified command and waits for it to complete.
Start starts the specified command but does not wait for it to complete.
您可能需要尝试使用 Run
来允许用户输入程序。或者,您可以使用 stdin 将另一个字符串重定向到命令中,但这可能比它的值(value)更复杂。
关于linux - 使用 GoLang 自动化 `mysql_secure_installation`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47066860/