我正在尝试从我的Go代码运行一个相当简单的bash命令。我的程序写出了IPTables配置文件,我需要发出命令以使IPTables从该配置刷新。在命令行中这非常简单:
/sbin/iptables-restore < /etc/iptables.conf
但是,我终生无法弄清楚如何使用exec.Command()发出此命令。我尝试了一些方法来实现此目的:
cmd := exec.Command("/sbin/iptables-restore", "<", "/etc/iptables.conf")
// And also
cmd := exec.Command("/sbin/iptables-restore", "< /etc/iptables.conf")
Run Code Online (Sandbox Code Playgroud)
毫不奇怪,这些都不起作用。我还尝试通过管道将文件名输入标准输入来将文件名输入命令:
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")
Run Code Online (Sandbox Code Playgroud)
这也不起作用,不足为奇。我可以使用stdin传递文件的内容,但是当我只能告诉iptables-restore要读取哪些数据时,这似乎很愚蠢。那么我怎么可能去运行命令/sbin/iptables-restore < /etc/iptables.conf?
小智 5
首先阅读此/etc/iptables.conf文件的内容,然后将其编写为cmd.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)
}
}
Run Code Online (Sandbox Code Playgroud)