具有输入重定向的Golang exec.command [英] Golang exec.command with input redirection
问题描述
我正在尝试从我的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")
那也不起作用,不足为奇.我可以使用stdin传递文件的内容,但是当我只能告诉iptables-restore要读取哪些数据时,这似乎很愚蠢.那么我怎么可能去运行命令/sbin/iptables-restore < /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
?
推荐答案
首先读取此/etc/iptables.conf
文件内容,然后将其写入cmd.StdinPipe()
中,如下所示:
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)
}
}
这篇关于具有输入重定向的Golang exec.command的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!