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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里