How to get output from os.exec in go

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

How to get output from os.exec in go

问题

我正在尝试从以下代码中获取系统输出:

cmdString := "lxc exec " + containerName + " -- ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1"
ip, err := exec.Command("bash", "-c", cmdString).Output()
fmt.Println(ip)

上述代码应该从一个 LXC 容器中获取 IP 地址。

实际的输出是 []

我还尝试了以下代码:

ip, err := exec.Command("lxc", "exec", containerName, "--", "ip addr show eth0", "|", "grep", "'inet\b'", "| awk '{print $2}'", "| cut -d/", "-f1").Output()
fmt.Println(ip)

我仍然只得到 [] 作为输出。

命令行的正确输出如下所示:

[root@localhost toolbox]# lxc exec simon -- ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1
10.183.201.38

有什么想法,我做错了什么吗?

英文:

I am trying to get the system output from the following code

cmdString := "lxc exec " + containerName + " -- ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1"
ip, err := exec.Command("bash", "-c", cmdString).Output()
fmt.Println(ip)

The above code should get the IP Address from an LXC Container.

The actual output from go is []

I have also tried the following

ip, err := exec.Command("lxc", "exec ", containerName, " --", "ip addr show eth0", "|", "grep", "'inet\b'", "| awk '{print $2}'", "| cut -d/", "-f1").Output()
fmt.Println(ip)

I still get just [] as output

The correct output from the command line is like below

[root@localhost toolbox]# lxc exec simon -- ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1
10.183.201.38

Any ideas what I am doing wrong?

答案1

得分: 1

阅读此代码后,您就可以了解如何读取结果的标准输出。

package main

import (
	"bytes"
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("/usr/bin/ls")
	buf := bytes.Buffer{}
	cmd.Stdout = &buf
	err := cmd.Run()

	fmt.Println(buf.String(), err)
}

这段代码使用Go语言编写,目的是执行/usr/bin/ls命令并读取其标准输出。首先,通过exec.Command函数创建一个cmd命令对象,指定要执行的命令为/usr/bin/ls。然后,创建一个bytes.Buffer对象buf,用于存储标准输出的内容。接下来,将cmd的标准输出重定向到buf,通过cmd.Stdout = &buf实现。最后,通过cmd.Run()执行命令,并将执行结果存储在buf中。最后,通过fmt.Println打印buf的内容和可能的错误信息。

这段代码的作用是执行ls命令并将结果打印出来。

英文:

Read this code then you can understand how to read result`s stdout

package main

import (
	"bytes"
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("/usr/bin/ls")
	buf := bytes.Buffer{}
	cmd.Stdout = &buf
	err := cmd.Run()

	fmt.Println(buf.String(), err)
}

huangapple
  • 本文由 发表于 2023年2月13日 05:13:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75430212.html
匿名

发表评论

匿名网友

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

确定