java 调用 linux 命令行 +使用管道、awk等命令进行数据处理的方法
这里用 sh -c "命令" 的方式是因为java里只能这么用,管道这边java处理不了,所以只能一次执行一条命令,但是在linux里用 sh -c 的方式返回的awk处理过的结果是有问题的,比如下面:
[root@192 ~]# sh -c "ping www.baidu.com -c 3 | awk -F '[ ]+' 'NR==8 {print $4}'" rtt min/avg/max/mdev = 3.514/3.778/4.232/0.329 ms
但是在java代码里却能够成功执行所需要的功能,可能是java执行后产生的是下面这样的效果:
[root@192 ~]# ping www.baidu.com -c 3 | awk -F '[ ]+' 'NR==8 {print $4}' 2.586/4.436/6.657/1.683
下面的java代码能够在 CentOS Linux release 7.6.1810 (Core) 下实现效果(取得ms值):
package com.kinome.surveillance.detect.connectivity; public class UpDateConnectivity { public static String upDateConnectivity(int rid, String ptLink) { String targetUrl = FilterHttpHeader.filterHttpHeader(ptLink); String canPingTargetUrl = ConnectionTimeMatchHandler.getFilteredResult(targetUrl, "(.*?)/"); // String TimeLine = RunCmdGetConnectionTimeHandler.getAverageTimeLine(canPingTargetUrl); // String connectTime = ConnectionTimeMatchHandler.getFilteredResult(TimeLine, "平均 = (.*?)ms").toString(); String avg1 = RunCmdGetConnectionTimeHandler.fetchAvg1(canPingTargetUrl); String connectTime = RunCmdGetConnectionTimeHandler.fetchAvg2(avg1); System.out.println("avg = " + connectTime + " ms"); return connectTime; } }
public static String fetchAvg1(String targetUrl) { BufferedReader br = null; String result = null; try { List<String> cmds = new LinkedList<String>(); cmds.add("sh"); cmds.add("-c"); cmds.add("ping " + targetUrl + " -c 3 | awk -F '[ ]+' 'NR==8 {print $4}'"); ProcessBuilder pb = new ProcessBuilder(cmds); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(3, TimeUnit.SECONDS); br = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line); } result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } return result; } public static String fetchAvg2(String avg1) { BufferedReader br = null; String result = null; try { List<String> cmds = new LinkedList<String>(); cmds.add("sh"); cmds.add("-c"); cmds.add("echo " + avg1 + " | awk -F '[/]+' '{print $2}'"); ProcessBuilder pb = new ProcessBuilder(cmds); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(3, TimeUnit.SECONDS); br = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line); } result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } return result; }