Golang exec.command with input redirection

前端 未结 2 1476
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 06:27

I\'m trying to run a fairly simple bash command from my Go code. My program writes out an IPTables config file and I need to issue a command to make IPTables refresh from t

相关标签:
2条回答
  • 2020-12-21 07:07

    first read this /etc/iptables.conf file content then write it to cmd.StdinPipe() like this:

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-21 07:09
    cmd := exec.Command("/usr/sbin/iptables-restore", "--binary", iptablesFilePath)
    _, err := cmd.CombinedOutput()
    if err != nil {
        return err
    }
    return nil
    

    this work fine on my Raspberry Pi3

    0 讨论(0)
提交回复
热议问题