tshark采集保存TLS协议字段数据
通过tshark抓取tls协议,参数包含抓包接口,源地址,目的地址,字段类型,采集长度,文件保存路径,但该代码是直接行写入,最终采集长度比所需长度一般大于等于一个数据包的相关字段长,有兴趣的同学可以自行优化。
代码如下:
static void Output(string captrueInterface, string tsharkPath, string src, string dst, string[] fields, int len, string outputFile)
{
// 创建进程
Process proc = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
// 给进程相关参数赋值
startInfo.FileName = tsharkPath;
//采集WLAN接口下源地址为10.0.0.1,目的地址为10.0.0.2 tls协议的enrypted application data 数据
//tshark -i WLAN -f "src host 10.0.0.1 and dst host 10.0.0.2" -T fields -e tls.app_data
//startInfo.Arguments = $"-i {captrueTnterface} -f \"src host {src} and dst host {dst}\" -T fields -e {string.Join(" -e ", fields)}";
startInfo.Arguments = $"-i {captrueInterface} -f \"src host {src} and dst host {dst}\" -T fields -e {string.Join(" -e ", fields)}";
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
proc.StartInfo = startInfo;
proc.Start(); //开启进程
//io流输入采集数据
using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputFile))
{
int writtenBytes = 0; // 控制采集数据的长度
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
if (!string.IsNullOrWhiteSpace(line)) // 采集非空行数据
{
writtenBytes += System.Text.Encoding.UTF8.GetBytes(line).Length;
file.WriteLine(line);
Console.WriteLine("长度:"+writtenBytes);
Console.WriteLine("written:"+line);
}
if (writtenBytes >= len) // 当采集数据达到要求退出循环停止采集
{
break;
}
}
}
proc.WaitForExit(1000);
proc.Close(); // 关闭进程