Surreal Dreams
Surreal Dreams

Reputation: 26380

exec.Command with input redirection

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 this config. This is very straightforward at the commandline:

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

However, I can't for the life of me figure out how to issue this command with exec.Command(). I tried a few things to accomplish this:

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

No surprise, neither of those worked. I also tried to feed the filename into the command by piping in the file name to stdin:

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")

That doesn't work either, no surprise. I can use stdin to pipe in the contents of the file, but this seems silly when I can just tell iptables-restore what data to go read. So how might I get Go to run the command /sbin/iptables-restore < /etc/iptables.conf?

Upvotes: 4

Views: 4233

Answers (2)

r3call.404
r3call.404

Reputation: 1

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

Upvotes: 0

user6169399
user6169399

Reputation:

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)
    }
}

Upvotes: 6

Related Questions