我正在尝试使用来自的示例从 golang 脚本执行 tskarh https://tutorialedge.net/golang/executing-system-commands-with-golang/
脚本工作正常,但我没有收到任何类型的输出
我想要得到的是:
- 持续运行脚本,
- 捕获一些数据包,
- 提取一些字段值,
- 并赋值给变量
有什么帮助吗?
package main
import (
"fmt"
"os/exec"
"runtime"
)
func execute() {
// here we perform the pwd command.
// we can store the output of this in our out variable
// and catch any errors in err
out, err := exec.Command("tshark", "-i", "em1").CombinedOutput()
// if there is an error with our execution
// handle it here
if err != nil {
fmt.Printf("%s", err)
}
fmt.Println("Command Successfully Executed")
// as the out variable defined above is of type []byte we need to convert
// this to a string or else we will see garbage printed out in our console
// this is how we convert it to a string
output := string(out[:])
// once we have converted it to a string we can then output it.
fmt.Println(output)
}
func main() {
fmt.Println("Simple Shell")
fmt.Println("---------------------")
if runtime.GOOS == "windows" {
fmt.Println("Can't Execute this on a windows machine")
} else {
execute()
}
}
最佳答案
我不知道 tshark,但这是一个可以连续工作的代码,你需要 os.Interrupt
和 select
。
package main
import (
"os"
"os/exec"
"os/signal"
)
func main() {
out := exec.Command("ping", "8.8.8.8")
f1, _ := os.OpenFile("./outfile.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755)
f2, _ := os.OpenFile("./errfile.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755)
out.Stdout = f1
out.Stderr = f2
defer func() {
f1.Close()
f2.Close()
}()
err := out.Run()
if err != nil {
panic(err)
}
var ctrlcInt chan os.Signal
ctrlcInt = make(chan os.Signal, 1)
signal.Notify(ctrlcInt, os.Interrupt)
for {
select {
case <-ctrlcInt:
break
default:
continue
}
}
return
}
此代码 ping 8.8.8.8
并将输出写入 outfile.txt
,当您按 ctrl+c
时它将退出。如果有错误,它将写入 errfile.txt
。您可以跟踪文件并查看输出。希望这会有所帮助。
关于go - 从 Go 脚本连续执行 tshark,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918178/