Runtime.getRuntime()。exec JAVA方法不能与tshark -o一起使用

时间:2013-01-23 09:41:25

标签: process runtime tshark

我正在尝试使用来自JAVA的tshark捕获数据包。[请在下面找到]

如果我尝试从终端(Ubuntu)的命令工作。但是从JAVA的投掷错误来看:

  

无效-o标志“column.format:”“source”,“

我尝试了以下替代方案[错误信息相同]

String[] cmdArray = {"tshark -i any -o column.format:\"source, %s, srcport, %uS\" -f \"port 80 or port 443\""};

和此:

String[] cmdArray = {"tshark -i any -o column.format:'source, %s, srcport, %uS' -f 'port 80 or port 443'"};


//CommandExc.java

import java.io.*;

import java.util.*;


public class CommandExc
{
public static void main (String args[])
 {

    //This worked Succcessfully
    //String[] cmdArray = {"tshark -D","sudo tshark -D"};

String[] cmdArray = {"tshark -i any -o column.format:\"\"source\", \"%s\",\"srcport\", \"%uS\"\" -f \"port 80 or port 443\""};

    for (String cmd: cmdArray) 
    {
         System.out.println("Executing command : "+cmd);
        try
        {
            Process proc = Runtime.getRuntime().exec(cmd); 
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String str = in.readLine();
            while(str != null)
            {
                System.out.println(str);
                //  res += str + "\n";
                str = in.readLine();
            }
            in.close();          

            BufferedReader in2 = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
            String str1 = in2.readLine();
            while(str1 != null)
            {
                System.out.println("Inside getErrorStream "+str1);
                //  res += str + "\n";
                str1 = in2.readLine();
            }
            in2.close();

            proc.waitFor();
            System.out.println("Exit value is : "+proc.exitValue());
            proc.destroy();
        }
        catch(IOException | InterruptedException e)
        {
            System.out.println("Exception on CommandExc class :" + e.toString());
                            e.printStackTrace();
        }
    } //end of for
  }
}

1 个答案:

答案 0 :(得分:0)

有效。参考http://ask.wireshark.org/questions/17881/issue-with-tshark-o

Java应用程序报告无效-o标志的原因是Runtime.exec方法的版本负责将提供的字符串拆分为单独的命令行参数。默认情况下,此方法使用空格,制表符,换行符,回车符和换页符。正如您所看到的,因为[column.format:\“\”source \“,] [\”%s \“,]之间存在空白字符,所以此版本的exec方法将它们视为2个不同的参数

解决方案是使用另一个版本的Runtime.exec方法,该方法将系统命令和参数作为数组参数。因此,您可以手动拆分命令行参数,并在数组参数中将它们定义为单独的字符串,如下所示:

进程proc = Runtime.getRuntime()。exec(new String [] {“tshark”,“ - i”,“any”,“ - o”,“column.format:\”source \“,\” %s \“,\”srcport \“,\”%uS \“”,“ - f”,“端口80或端口443”});