问题答案

写了个小程序,批量ssh远端服务器操作,并且将结果保存到本地.

现在使用的方法:

使用exec.Command 执行命令,获取cmd.Stdout ,并且结果outf.WriteString到文件.

如果场景变成是grep 一个比较大的日志,有比较大的标准输出,这个时候是全部都读取到内存再一次性写到文件中么? 是否有办法可以进行优化?谢谢. 

标签: go
答案

多谢huan du 和felix ,使用os/exec就可以处理所有的内容了.

Package exec runs external commands. It wraps os.StartProcess to make it easier to remap stdin and stdout, connect I/O with pipes, and do other adjustments.

package main

import (
"fmt"
"io"
"log"
"os"
"os/exec"
)

func checkError(err error) {
if err != nil {
log.Fatalf("Error: %s", err)
}
}

func main() {
// Replace `ls` (and its arguments) with something more interesting
cmd := exec.Command("ssh", "1.1.1.1","find /")

// Create stdout, stderr streams of type io.Reader
stdout, err := cmd.StdoutPipe()
checkError(err)
stderr, err := cmd.StderrPipe()
checkError(err)

// Start command
err = cmd.Start()
checkError(err)

// Don't let main() exit before our command has finished running
defer cmd.Wait() // Doesn't block

// Non-blockingly echo command output to terminal
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)

// I love Go's trivial concurrency :-D
fmt.Printf("Do other stuff here! No need to wait.\n\n")

举一反三