如何使用Golang执行'top'命令输出

I want to write the 'top' command's output to another file. But when I tried it with the below code, I get the below error:

'exit status 1'.

Here is my code:

package main

import "os/exec"

func main() {
    app := "top"
    cmd := exec.Command(app)
    stdout, err := cmd.Output()

    if err != nil {
        println(err.Error())
        return
    }

    print(string(stdout))
}

Any help is greatly appreciated. Thanks in advance.

From man page for "top", -b option is good for sending output to another program (no color, no anything) as plain text, and -n is the number of frame it will iterate before stopping. Without -n it will iterate infinite time.

 func main() {
      app := "top"
      arg0 := "-b"
      arg1 := "-n"
      arg2 := "1"

      cmd := exec.Command(app, arg0, arg1, arg2)
      stdout, err := cmd.Output()

      if err != nil {
        println(err.Error())
        return
      }

      print(string(stdout))
    }
s := fmt.Sprintf(`"top -bn2 | fgrep 'Cpu(s)' | tail -1"`, host)
log.Printf("top = %s
", s)
cmd := exec.Command("bash", "-c", s)
b, e := cmd.Output()
if e != nil {
    log.Printf("failed due to :%v
", e)
    panic(e)
}
log.Printf("%v
", string(b))
raw := string(b)

This is what you could potentially do if you are planning to run top in batch mode. Note tail -1 maybe of value if you wanted to pick last one instead of capturing everything, and fgrep useful if you are to grep for a specific fields - however it is not necessary.

For reference, here are other ways to run top.

c := exec.Command("top")
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Run()

This is for local. If you are looking via ssh, use this -

c := exec.Command("ssh", "-t", "localhost", "top")
c.Stdin = os.Stdin
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Run()

If you want to start a server, and connect as a client via telnet and show on telnet screen result of top command (common case when running top remotely using a go introspecting server perhaps) use this -



    func main() {
        l, _ := net.Listen("tcp", "127.0.0.1:12345")
        for {
            c, _ := l.Accept()
            go func() {
                handle(&c)
            }()
        }
    }
    func handle(c *net.Conn) {
        cmd := exec.Command("top")
        cstdout, _ := cmd.StdoutPipe()
        go io.Copy(bufio.NewWriter(*c), bufio.NewReader(cstdout))
        cmd.Run()
    }


If you are building a terminal using telnet and ssh to run generic commands like app use this library - https://github.com/kr/pty

Edit Going to make it better ... here's an example that works for PTY, scenario is if you use ssh -t to run a command want to interact with telneting from this server type setup e.g. top use this :



       cmd := exec.Command("ssh", "-t", "localhost", "top")
        f, _ := pty.Start(cmd)
        go io.Copy(bufio.NewWriter(*c), f)
        go io.Copy(f, bufio.NewReader(*c))
        go io.Copy(bufio.NewWriter(*c), os.Stdin)
        cmd.Run()