I am trying to execute some bash commands within some java code. The goal is to get the rx and tx data. I got a function for the command execution. I have tested the function with other commands and it works fine.
But in this example the variable interfaceName
is always empty:
public static void main(String args[]) {
String interfaceCommand = "route | grep default | tr -s ' ' | cut -d ' ' -f 8";
String interfaceName = executeCommand(interfaceCommand);
String getRXCommand = "cat /sys/class/net/" + interfaceName + "/statistics/rx_bytes";
String rxData = executeCommand(getRXCommand);
String getTXCommand = "cat /sys/class/net/" + interfaceName + "/statistics/tx_bytes";
String txData = executeCommand(getTXCommand);
System.out.println(interfaceName);
System.out.println(getTXCommand);
System.out.println(getRXCommand);
}
private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
If I set the variable interfaceName
manually to enp0s31f6
the commands to get the rx and tx data are working fine (just on my test-PC). But i like to use the program on several PCs and the interface name is not always the same. So i need to get the interface name first.
It seems to be a problem if the command uses the | because i tried some other command variations.
- With
ip -o link show | grep ' UP ' | awk '{print $2}'
the variable is empty. With
ls /sys/class/net/ | grep enp
the variable is/sys/class/net/: enp0s31f6 lo vmnet1 vmnet8
That is not the proper return value for the command. And as I said other commands, without |, are working fine...
I am not quite sure where my error is neither how to start searching for a proper solution. Do i have somehow to escape the |? Or is there another solution to get the interface name?