【问题标题】:exec.Command with input redirection带有输入重定向的 exec.Command
【发布时间】:2016-07-10 02:19:04
【问题描述】:

我正在尝试从我的 Go 代码中运行一个相当简单的 bash 命令。我的程序写出一个 IPTables 配置文件,我需要发出一个命令来使 IPTables 从这个配置中刷新。这在命令行中非常简单:

/sbin/iptables-restore < /etc/iptables.conf

但是,我终其一生都无法弄清楚如何使用 exec.Command() 发出此命令。我尝试了一些方法来实现这一点:

cmd := exec.Command("/sbin/iptables-restore", "<", "/etc/iptables.conf")
// And also
cmd := exec.Command("/sbin/iptables-restore", "< /etc/iptables.conf")

毫不奇怪,这些都不起作用。我还尝试通过将文件名管道输入到标准输入来将文件名输入命令:

cmd := exec.Command("/sbin/iptables-restore")
stdin, err := cmd.StdinPipe()
if err != nil {
    log.Fatal(err)
}

err = cmd.Start()
if err != nil {
    log.Fatal(err)
}

io.WriteString(stdin, "/etc/iptables.conf")

这也不起作用,不足为奇。我可以使用标准输入管道输入文件的内容,但是当我可以告诉 iptables-restore 读取哪些数据时,这似乎很愚蠢。那么如何让 Go 运行命令 /sbin/iptables-restore &lt; /etc/iptables.conf

【问题讨论】:

    标签: bash go


    【解决方案1】:

    首先读取此/etc/iptables.conf 文件内容,然后将其写入cmd.StdinPipe(),如下所示:

    package main
    
    import (
        "io"
        "io/ioutil"
        "log"
        "os/exec"
    )
    
    func main() {
        bytes, err := ioutil.ReadFile("/etc/iptables.conf")
        if err != nil {
            log.Fatal(err)
        }
        cmd := exec.Command("/sbin/iptables-restore")
        stdin, err := cmd.StdinPipe()
        if err != nil {
            log.Fatal(err)
        }
        err = cmd.Start()
        if err != nil {
            log.Fatal(err)
        }
        _, err = io.WriteString(stdin, string(bytes))
        if err != nil {
            log.Fatal(err)
        }
    }
    

    【讨论】:

    • 我想到了这一点,并用静态字符串模拟了它作为测试。有用。但是,我希望我可以做到这一点,而无需将数据内容转储到这样的管道中。但是,如果这是唯一的方法,那就必须这样做。
    • 调用 `exec.Command("/sbin/iptables-restore", "exec.Command("/sbin/iptables-restore < /etc/iptables.conf"),但这也不起作用。如果出现错误:找不到文件(在我的情况下),您可以调用一个名为“/sbin/iptables-restore
    【解决方案2】:
    cmd := exec.Command("/usr/sbin/iptables-restore", "--binary", iptablesFilePath)
    _, err := cmd.CombinedOutput()
    if err != nil {
        return err
    }
    return nil
    

    这在我的 Raspberry Pi3 上运行良好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2012-02-19
      • 2012-06-08
      • 2015-06-19
      • 1970-01-01
      • 2018-03-20
      相关资源
      最近更新 更多