Ping.java 5.6 KB
package com.sitech.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.adventnet.utils.agent.RunCmd;

/**
 * Ping工具类
 * 
 * @author LINXC
 */
public class Ping {
	public static Logger logger= Logger.getLogger(Ping.class);
	
	public static final String STATE = "STATE";
	public static final String MINRTT = "MINRTT";
	public static final String AVGRTT = "AVGRTT";
	public static final String MAXRTT = "MAXRTT";

	public static boolean ping1(String ipAddr) {
		boolean isReacheable = false;

		Map<String, String> result = ping2(ipAddr);
		if (result.get(STATE) != null && result.get(STATE).equals("UP")) {
			isReacheable = true;
		}
		logger.info("ping " + ipAddr + ":\t" + isReacheable);
		return isReacheable;
	}

	public static Map<String, String> ping2(String ipAddr) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			result = new PingUtils().excute(ipAddr);
		} catch (Exception e) {
			logger.error("Exception while ping " + ipAddr, e);
		}

		logger.info("ping " + ipAddr + ":\t" + JSONUtil.toJSON(result));
		return result;
	}

	public static void main(String[] args) {
//		if (args.length < 1 || args[0].trim().equals("-h")) {
//			System.err.println("Usage: com.sitech.util.Ping <remote-ip>");
//            System.exit(1);
//		}
//		Ping.ping1(args[0]);
		Ping.ping1("172.21.1.171");
	}
}

class PingUtils {
	public Map<String, String> excute(String ipAddr) {
		Map<String, String> map = new HashMap<String, String>();

		String os = System.getProperty("os.name").toLowerCase();
		System.out.println("-- os:\t" + os);
		String command = "";

		if (os.indexOf("windows") >= 0) {
			command = "ping -n 3 " + ipAddr;
		} else if (os.indexOf("aix") >= 0) {
			command = "ping " + ipAddr + " 9 3";
		} else if (os.indexOf("sunos") >= 0 || os.indexOf("solaris") >= 0) {
			command = "/usr/sbin/ping -s " + ipAddr + " 9 5";
		} else if (os.indexOf("hp-ux") >= 0) {
			command = "ping " + ipAddr + " -n 3 -m 3";
		} else if (os.indexOf("linux") >= 0) {
            command = "/bin/ping -c 3 -w 3 " + ipAddr;
        } else if (os.indexOf("mac") >= 0) {
            command = "/sbin/ping -c 3 " + ipAddr;
        }

		System.out.println(command);

		String result = excuteCmd(command);

		System.out.println(result);

		String state = "DOWN";
		String min = "-1";
		String avg = "-1";
		String max = "-1";

		if (os.indexOf("windows") >= 0) {
			if (result != null && result.indexOf("100% loss") < 0) {
				state = "UP";
				result = result.substring(result.indexOf("Minimum"));
				String[] temp = result.split(",");

				min = temp[0].replace("Minimum =", "").replace("ms", "").trim();
				avg = temp[1].replace("Maximum =", "").replace("ms", "").trim();
				max = temp[2].replace("Average =", "").replace("ms", "").trim();
			}
		} else if (os.indexOf("aix") >= 0) {
			if (result != null && result.indexOf("100% packet loss") < 0) {
				state = "UP";
				result = result.substring(result.indexOf("min/avg/max"));
				String[] temp1 = result.split("=");
				temp1[1] = temp1[1].replace("ms", "").trim();
				String[] temp2 = temp1[1].split("/");

				min = temp2[0].trim();
				avg = temp2[1].trim();
				max = temp2[2].trim();
			}
		} else if (os.indexOf("sunos") >= 0 || os.indexOf("solaris") >= 0) {
			if (result != null && result.indexOf("100% packet loss") < 0) {
				state = "UP";
				
				result = result.substring(result.indexOf("min/avg/max/stddev"));
				String[] temp1 = result.split("=");
				temp1[1] = temp1[1].replace("ms", "").trim();
				String[] temp2 = temp1[1].split("/");
				min = temp2[0].trim();
				avg = temp2[1].trim();
				max = temp2[2].trim();
			}
		} else if (os.indexOf("hp-ux") >= 0) {
			if (result != null && result.indexOf("100% packet loss") < 0) {
				state = "UP";
				
				result = result.substring(result.indexOf("min/avg/max"));
				String[] temp1 = result.split("=");
				temp1[1] = temp1[1].replace("ms", "").trim();
				String[] temp2 = temp1[1].split("/");
				min = temp2[0].trim();
				avg = temp2[1].trim();
				max = temp2[2].trim();
			}
		} else if (os.indexOf("linux") >= 0) {
            if (result != null && result.indexOf("100% packet loss") < 0) {
                state = "UP";

                result = result.substring(result.indexOf("min/avg/max/mdev"));
                String[] temp1 = result.split("=");
                temp1[1] = temp1[1].replace("ms", "").trim();
                String[] temp2 = temp1[1].split("/");
                min = temp2[0].trim();
                avg = temp2[1].trim();
                max = temp2[2].trim();
            }
        } else if (os.indexOf("mac") >= 0) {
            if (result != null && result.indexOf("100.0% packet loss") < 0) {
                state = "UP";

                result = result.substring(result.indexOf("min/avg/max/stddev"));
                String[] temp1 = result.split("=");
                temp1[1] = temp1[1].replace("ms", "").trim();
                String[] temp2 = temp1[1].split("/");
                min = temp2[0].trim();
                avg = temp2[1].trim();
                max = temp2[2].trim();
            }
        }

		map.put(Ping.STATE, state);
		map.put(Ping.AVGRTT, avg);
		map.put(Ping.MINRTT, min);
		map.put(Ping.MAXRTT, max);

		return map;
	}

	private String excuteCmd(String command) {
		// 超时时间60秒
		long timeout = 60000;

		RunCmd runcmd = new RunCmd(command);
		long startTime = new Date().getTime();

		runcmd.start();
		while (runcmd.isAlive()) {
			try {
				Thread.sleep(1000L);
			} catch (Exception e) {
			}

			if (new Date().getTime() > startTime + timeout) {
				runcmd.stopCommand();
				return null;
			}
		}
		return runcmd.stdout.toString();
	}

}