当前位置 : 主页 > 编程语言 > java >

Java执行Ping命令代码

来源:互联网 收集:自由互联 发布时间:2022-06-22
Java执行Ping命令代码 import org . slf4j . Logger ; import org . slf4j . LoggerFactory ; import java . io . BufferedReader ; import java . io . IOException ; import java . io . InputStreamReader ; import java . util . regex . Matcher ;


Java执行Ping命令代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author Jack魏
* @date 2021-03-22
*/
public class PingUtils {

private static Logger logger = LoggerFactory.getLogger(PingUtils.class);
/**
* 次数
*/
private static final int PING_TIMES = 3;
/**
* 超时时间
*/
private static final int TIME_OUT = 3;
/**
* windows 正则表达式
*/
private static Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)", Pattern.CASE_INSENSITIVE);
/**
* windows 指令
*/
private static String countCommand = "-n" + " " + PING_TIMES + " -w " + TIME_OUT;
/**
* 与运行环境交互
*/
private static final Runtime RUNTIME = Runtime.getRuntime();

static {
// 检测是不是linux服务器
boolean isLinux = System.getProperty("os.name").toLowerCase().contains("linux");
if (isLinux){
// 执行linux 指令
pattern = Pattern.compile("(icmp_seq=\\d+)", Pattern.CASE_INSENSITIVE);
countCommand = "-c" + " " + PING_TIMES + " -w " + TIME_OUT;
}
}

/**
* @param ip
* @return true ping通 否则不通
*/
public static boolean ping(String ip) {
String pingCommand = "ping " + ip + " " + countCommand;
Process p = null;
try {
// 执行命令并获取输出
p = RUNTIME.exec(pingCommand);
if (p == null) {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}

try(BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
// 逐行检查输出,计算类似出现=23ms TTL=62字样的次数
int connectedCount = 0;
String line = null;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line);
}
// 出现的次数>=测试次数则返回真
return connectedCount >= PING_TIMES;
} catch (Exception ex) {
logger.error("ping异常---", ex);
return false;
}
}
/**
* 若line含有18ms TTL=16字样,说明已经ping通,返回1,否則返回0.
*/
private static int getCheckResult(String line) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return 1;
}
return 0;
}

public static void main(String[] args) {
System.out.println(ping("192.168.50.136"));
System.out.println(ping("192.168.50.24"));
System.out.println(ping("192.168.50.66"));
}
}


上一篇:Java代码执行Linux脚本
下一篇:没有了
网友评论