duanchen1937 2016-07-10 02:19 采纳率: 0%
浏览 129
已采纳

具有输入重定向的Golang执行命令

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?

  • 写回答

2条回答 默认 最新

  • doujinge9648 2016-07-10 02:42
    关注

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 List<Class>有参构造
  • ¥20 搭建三相栅极电路后高侧浮动地VS存在电容特性
  • ¥20 云卓h12pro 数传问题
  • ¥20 请问有人知道怎么用工艺库里面的sdb文件通过virtuoso导出来library里面每个cell的symbol吗?
  • ¥20 海思 nnie 编译 报错
  • ¥50 决策面并仿真,要求有仿真结果图
  • ¥15 springboot接入微信支付SDK
  • ¥50 大区域的遥感影像匹配 怎么做啊
  • ¥15 求解答:pytorch跑yolov8神经网络受挫
  • ¥20 Js代码报错问题不知道怎么解决