前幾天接到個任務,要求批量ping域名,找了網上好多資料都沒有好的方法,隻能自己試着用外部工具fping輔助,做了一個工具類,用了下還可以
首先安裝fping
yum -y install fping
然後給普通使用者權限
chown root:root /usr/local/sbin/fping
chmod u+s /usr/local/sbin/fping
下面是工具類
public class NetUtils {
private static final String ALIVE = "alive";
private static final String FPING = "fping ";
private static final String IS = " is ";
private static final String COLON = ":";
private static final String CHARSET = "UTF-8";
private static final String UNREACHABLE= "unreachable";
//單獨ping一個的,格式 fping baidu.com
public static boolean ping(String ipAddress) {
BufferedReader br = null;
String pingCommand = FPING + ipAddress;
try {
Process p = Runtime.getRuntime().exec(pingCommand);
br = new BufferedReader(new InputStreamReader(p.getInputStream(), CHARSET));
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains(ALIVE)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
//ping多個的,格式 fping baidu.com douyin.com 12.45.43.211 多個域名網址中間以空格隔開,傳回的是域名是否線上: key<域名> value<alive或unreachable>
public static Map<String, String> fPing(String ipAddress) {
BufferedReader br = null;
String pingCommand = FPING + ipAddress;
HashMap<String, String> map = new HashMap<>();
try {
Process p = Runtime.getRuntime().exec(pingCommand);
br = new BufferedReader(new InputStreamReader(p.getInputStream(), CHARSET));
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains(IS)) {
String[] split = line.split(IS);
map.put(split[0], split[1]);
}else {
String[] split = line.split(COLON);
map.put(split[0],UNREACHABLE);
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
}
試了一下,200多個IP/域名,用javaping跑了5分鐘,這個用了30秒