Go 코드에서 매우 간단한 bash 명령을 실행하려고합니다. 내 프로그램은 IPTables 구성 파일을 작성하고이 구성에서 IPTables를 새로 고치려면 명령을 실행해야합니다. 이 명령 줄에서 매우 간단하다 :Golang exec.command 입력 리디렉션
/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 - 어떤 데이터를 읽을지를 복원 할 수 있다고 말할 때 어리석은 것처럼 보입니다. 그럼 내가 어떻게 명령을 실행하려면 이동 /sbin/iptables-restore < /etc/iptables.conf
?
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)
}
}
나는이 생각했던, 그리고 테스트와 같은 정적 문자열을 조롱했다 : –
'exec.Command ("/ sbin/iptables-restore", "<", "/etc/iptables.conf")와 같은 호출은 작동하지 않습니다 : "<"와 "/etc/iptables.conf"는 "/ sbin/iptables-restore"로 args합니다. 나는 당신이'exec.Command ("/ sbin/iptables-restore