go - 从 Go 脚本连续执行 tshark

标签 go tshark

我正在尝试使用来自的示例从 golang 脚本执行 tskarh https://tutorialedge.net/golang/executing-system-commands-with-golang/

脚本工作正常,但我没有收到任何类型的输出

我想要得到的是:

  1. 持续运行脚本,
  2. 捕获一些数据包,
  3. 提取一些字段值,
  4. 并赋值给变量

有什么帮助吗?

https://pastebin.com/PeAz7vh9

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.Interruptselect

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/

相关文章:

numbers - Go 中 int 类型的最大值

terminal - 格式化 tshark 输出

linux - 通过本地用户名进行 Tshark 日志记录

xml - 如何访问 pyshark 中嗅探的 http 数据包中包含的 xml 有效负载的文本表示?

go - slice 内 slice golang

macos - 运行最新版本时没有 "up to date"信息?

linux - 如何持续将嗅探到的数据包提供给kafka?

wireshark - tshark 输出所有字段?

file-upload - golang上传文件err运行时错误索引超出范围

c - 接口(interface) Go 与 C 库