具有输入重定向的Golang执行命令
我正在尝试从我的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")
毫不奇怪,这些都不起作用。我还尝试通过管道将文件名输入标准输入来将文件名输入命令:
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?
回答:
首先阅读此/etc/iptables.conf
文件的内容,然后将其编写为cmd.StdinPipe()
:
package mainimport (
"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执行命令 的全部内容, 来源链接: utcz.com/qa/415310.html