问题描述
我正在尝试从我的Go代码运行一个相当简单的bash命令.我的程序写出一个IPTables配置文件,我需要发出命令以使IPTables从该配置刷新.在命令行中,这非常简单:
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
但是,我终生无法弄清楚如何使用exec.Command()发出此命令.我尝试了一些方法来实现此目的:
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")
/sbin/iptables-restore < /etc/iptables.conf
/sbin/iptables-restore < /etc/iptables.conf
推荐答案
/etc/iptables.confcmd.StdinPipe()
/etc/iptables.confcmd.StdinPipe()
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)
}
}
这篇关于具有输入重定向的Golang exec.command的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!