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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵