[Java]ping或扫描端口的工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Discovery {
	 PrintStream out = null; 
	 
	 public Discovery(){		 
	 }
	 
	 public Discovery(PrintStream out){
		 this.out = out;
	 }

	/**
	 * 对指定的ip(数组)进行ping探测
	 * 
	 * @param ips ip数组       
	 * @return 返回格式为 ip:是否成功
	 */
	public LinkedHashMap<String, Boolean> ping(List<String> ips) {
		LinkedHashMap<String, Boolean> ret = new LinkedHashMap<String, Boolean>();
		Map<String, String> args = new HashMap<String, String>();
		BufferedReader br = null;
		for (String ip : ips) {
			args.put("ip", ip);
			String value = SystoolkitConfigure.getValue("ping.command", args);
			// 获得JVM的运行环境
//			Runtime r = Runtime.getRuntime();
			// 创建一个ping命令进程
			try {
				Process p = Runtime.getRuntime().exec(value);
				StringBuilder sb = new StringBuilder();
				String line = null;

				br = new BufferedReader(new InputStreamReader(
						p.getInputStream()));
				while ((line = br.readLine()) != null) {
					sb.append(line.trim());
					sb.append(‘\n‘);
				}
				br.close();

				br = new BufferedReader(new InputStreamReader(
						p.getErrorStream()));
				while ((line = br.readLine()) != null) {
					sb.append(line.trim());
					sb.append(‘\n‘);
				}
				br.close();

				String os = SystoolkitConfigure.getOS().toLowerCase();
				if (-1 != os.indexOf("windows")) {
					int index = sb.toString().indexOf("Packets: Sent = 1, Received = 1,");
					ret.put(ip, index != -1);
					if(null!=out) {
						out.println(ip+":"+(index != -1));
						out.flush();
					}
				} else if (-1 != os.indexOf("linux")) {
					int index = sb.toString().indexOf("1 packets transmitted, 1 received");
					ret.put(ip, index != -1);
					if(null!=out) {
						out.println(ip+":"+(index != -1));
						out.flush();
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
//				e.printStackTrace();
			} 
		}

		return ret;
	}

	/**
	 * 对指定网段的指定ip范围的机器,进行ping探测
	 * 
	 * @param networkSection
	 *            网段,例:192.168.2
	 * @param startIp
	 *            开始ip,包含此ip,值>0
	 * @param endIp
	 *            结束ip,包含此ip,值<255
	 * @return ping探测结果
	 */
	public LinkedHashMap<String, Boolean> ping(String networkSection,
			int startIp, int endIp) {
		List<String> ips = new ArrayList<String>();
		if (startIp <= 0 || endIp >= 255) {
			throw new IllegalArgumentException("startIp<=0 or endIp>=255.");
		}
		for (int i = startIp; i <= endIp; i++) {
			// ips.add(String.format("%s.%d", networkSection,i));
			ips.add(networkSection + "." + i);
		}
		return ping(ips);
	}

	/**
	 * 此方法相当于ping(networkSection,1,254)
	 * 
	 * @param networkSection
	 * @return
	 */
	public LinkedHashMap<String, Boolean> ping(String networkSection) {
		return ping(networkSection, 1, 254);
	}

//	public LinkedHashMap<String, Boolean> scanPort(String networkSection,
//			int startIp, int endIp, String port) {
//		// throw new RuntimeException();
//		LinkedHashMap<String, Boolean> ret = new LinkedHashMap<String, Boolean>();
//		List<Integer> ports = new ArrayList<Integer>();
//		List<String> ips = new ArrayList<String>();
//		if (startIp <= 0 || endIp >= 255) {
//			throw new IllegalArgumentException("startIp<=0 or endIp>=255.");
//		}
//		for (int i = startIp; i <= endIp; i++) {
//			ips.add(networkSection + "." + i);
//		}
//		String[] ss = port.split(",");
//		for (String s : ss) {
//			if (-1 != s.indexOf(‘-‘)) {
//				String[] range = s.split("-");
//				for (int i = Integer.parseInt(range[0]), end = Integer
//						.parseInt(range[1]); i <= end; i++) {
//					ports.add(i);
//				}
//			} else {
//				ports.add(Integer.parseInt(s));
//			}
//		}
//		Socket client = null;
//		for (String ip : ips) {
//			for (Integer p : ports) {
//				try {
//					client = new Socket();
//					client.connect(new InetSocketAddress(ip, p), 300);
//					ret.put(ip, true);
//				} catch (Exception ex) {
//					ret.put(ip, false);
//				} finally {
//					try {
//						if (null != client)
//							client.close();
//					} catch (Exception ex) {
//					}
//				}
//			}
//
//		}
//		return ret;
//	}

//	public void scanPort(List<String> ips, String port, PrintStream out) {
//		List<Integer> ports = new ArrayList<Integer>();
//
//		String[] ss = port.split(",");
//		for (String s : ss) {
//			if (-1 != s.indexOf(‘-‘)) {
//				String[] range = s.split("-");
//				for (int i = Integer.parseInt(range[0]), end = Integer
//						.parseInt(range[1]); i <= end; i++) {
//					ports.add(i);
//				}
//			} else {
//				ports.add(Integer.parseInt(s));
//			}
//		}
//
//		Socket client = null;
//		for (String ip : ips) {
//			for (Integer p : ports) {
//				try {
//					client = new Socket();
//					client.connect(new InetSocketAddress(ip, p), 300);
//					// ret.add(ip+":"+p);
//					out.println(ip + ":" + p);
//					out.flush();
//				} catch (Exception ex) {
//				} finally {
//					try {
//						if (null != client)
//							client.close();
//					} catch (Exception ex) {
//					}
//				}
//			}
//		}
//
//		out.close();
//	}

	public List<String> scanPort(String networkSection,
			int startIp, int endIp, String port) {
		List<String> ips = new ArrayList<String>();

		if (startIp <= 0 || endIp >= 255) {
			throw new IllegalArgumentException("startIp<=0 or endIp>=255.");
		}
		for (int i = startIp; i <= endIp; i++) {
			ips.add(networkSection + "." + i);
		}

		return scanPort(ips,port);
	}

	public List<String> scanPort(List<String> ips, String port) {
		List<String> ret = new ArrayList<String>();
		List<Integer> ports = new ArrayList<Integer>();

		String[] ss = port.split(",");
		for (String s : ss) {
			if (-1 != s.indexOf(‘-‘)) {
				String[] range = s.split("-");
				for (int i = Integer.parseInt(range[0]), end = Integer
						.parseInt(range[1]); i <= end; i++) {
					ports.add(i);
				}
			} else {
				ports.add(Integer.parseInt(s));
			}
		}

		Socket client = null;
		for (String ip : ips) {
			for (Integer p : ports) {
				try {
					client = new Socket();
					client.connect(new InetSocketAddress(ip, p), 300);

					ret.add(ip + ":" + p);

					if(null!=out){
						out.println(ip + ":" + p);
						out.flush();
					}
				} catch (Exception ex) {
//					System.out.println(ex.getMessage());
				} finally {
					try {
						if (null != client)
							client.close();
					} catch (Exception ex) {
					}
				}
			}

		}

		return ret;
	}
}

配置扫描

import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ExecutorService;

/**
 * 
 * @author shanl
 *
 */
public class SystoolkitConfigure implements Runnable{
	private static final String default_configure = "systoolkit_default";
	private static String user_configure = "systoolkit";
	//private int scanInterval = 1000*60*5;
	private int scanInterval = 1000*5;
	private static Properties config = new Properties();
	boolean isService = false;

	/**
	 * 使用默认文件名的配置文件
	 */
	public SystoolkitConfigure(){
	}

	/**
	 * 
	 * @param userConfig 用户自定义配置文件
	 */
	public SystoolkitConfigure(String userConfig){
		user_configure = userConfig;
	}	

	public void run() {
		ResourceBundle confRes = ResourceBundle.getBundle(default_configure);
		Enumeration<String> keys = confRes.getKeys();
		while(keys.hasMoreElements()){
			String key = keys.nextElement();
			String value = confRes.getString(key);
			if(null!=value) config.setProperty(key, value);
		}

		Properties sysProp = System.getProperties();
		config.putAll(sysProp);

		for(;;){
			try{
				confRes = ResourceBundle.getBundle(user_configure);
				keys = confRes.getKeys();
				while(keys.hasMoreElements()){
					config.setProperty(keys.nextElement(), confRes.getString(keys.nextElement()));
				}
			}catch(Exception ex){}

			if(isService) try{Thread.sleep(scanInterval); }catch(Exception ex){}
			else break;
		}
	}

	/**
	 * 线程方式启动
	 * @param threadPool 线程池容器,可以为null
	 */
	public void start(ExecutorService threadPool){
		isService = true;
		Thread t = new Thread(this,this.getClass().getSimpleName());
		if(null==threadPool){
			t.start();
		}else{
			threadPool.execute(t);
		}
	}

	public void stop(){
		this.isService = false;
	}

	/**
	 * 设置配置文扫描间隔
	 * @param interval
	 */
	public void setScanInterval(int interval){
		this.scanInterval = interval;
	}

	/**
	 * 从配置文件中取值
	 * @param key
	 * @return 如果找不到(或这个键就没有值),则返回""
	 */
	public static String getValue(String key){
		String os = getOS().toLowerCase();
		String ret = "";

		if(-1!=os.indexOf("windows")){
			ret = config.getProperty(key+".windows","");
		}else if(-1!=os.indexOf("linux")){
			ret = config.getProperty(key+".linux","");
		}

		if("".equals(ret)){
			ret = config.getProperty(key, "");
		}
		return ret;
	}

	/**
	 * 从配置文件中取值,并把${args.key}的格式替换为args.value
	 * @param key 
	 * @param args 参数
	 * @return
	 */
	public static String getValue(String key,Map<String,String> args){
		String value = getValue(key);
		if("".equals(value.trim())) return "";

		Set<Map.Entry<String,String>>values = args.entrySet();
		for(Map.Entry<String,String> i: values){
			value = value .replaceAll("\\${1}\\{{1}"+i.getKey()+"\\}{1}", i.getValue());
		}

		return value;
	}

	public static
	String getOS(){
		return System.getProperty("os.name");
	}
}

systoolkit.properties

test=default test.
test.linux=linux test.
test.windows=windows test.
ping.command.linux=ping -c 1 -s 8 ${ip}
ping.command.windows=ping -n 1 -w 1 -l 8 ${ip}

端口扫描测试

/**
	 * 扫描端口
	 */
	static void t2(){
		new SystoolkitConfigure().run();

		Discovery d = new Discovery(System.out);
//		d.scanPort("192.168.2", 1, 254, "22,23,80");

		List<String> ips = new ArrayList<String>();
		ips.add("192.168.2.22");
		ips.add("192.168.2.23");
		ips.add("192.168.2.54");
		ips.add("192.168.2.55");
		d.scanPort(ips,"22,23,80,100-200");
	}
[[email protected] ~]# java -jar discovery.jar
192.168.2.1:23
192.168.2.1:80
192.168.2.10:80
192.168.2.23:22
192.168.2.37:23
192.168.2.54:22
192.168.2.54:23
192.168.2.56:80
192.168.2.57:22
192.168.2.57:23
192.168.2.100:22
192.168.2.107:22
192.168.2.141:80
192.168.2.154:22
192.168.2.154:23
192.168.2.182:22
192.168.2.183:22
192.168.2.201:22

ping探测测试

/**
	 * ping扫描
	 */
	static void t1(){
		new SystoolkitConfigure().run();

		Discovery d = new Discovery(System.out);
		Map<String,Boolean> ret = d.ping("192.168.2");
//		System.out.println(ret);

		List<String> ips = new ArrayList<String>();
		ips.add("192.168.2.22");
		ips.add("192.168.2.23");
		ips.add("192.168.2.54");
		ips.add("192.168.2.55");

		ret = d.ping(ips);
	}
[[email protected] ~]# java -jar discovery.jar
192.168.2.1:true
192.168.2.2:false
192.168.2.3:false
192.168.2.4:false
192.168.2.5:false
192.168.2.6:true
192.168.2.7:false
192.168.2.8:true
192.168.2.9:false
192.168.2.10:true
192.168.2.11:true
192.168.2.12:false
192.168.2.13:false
192.168.2.14:false
192.168.2.15:false
192.168.2.16:false
192.168.2.17:false
192.168.2.18:true
192.168.2.19:false
192.168.2.20:false
192.168.2.21:false
192.168.2.22:true
192.168.2.23:true
192.168.2.24:false
192.168.2.25:true
192.168.2.26:false
192.168.2.27:true
192.168.2.28:false
192.168.2.29:false
192.168.2.30:true
192.168.2.31:false
192.168.2.32:true
192.168.2.33:false
192.168.2.34:false
192.168.2.35:false
192.168.2.36:false
192.168.2.37:true
时间: 2024-07-30 10:07:59

[Java]ping或扫描端口的工具类的相关文章

Java字符串转16 进制工具类Hex.java

原文:Java字符串转16 进制工具类Hex.java 源代码下载地址:http://www.zuidaima.com/share/1550463378410496.htm Java 字符串转 16 进制工具类 Hex.java 实现 16进制 0xfecd .. 和 java 字符串之间的互转换! 如果做开发,通常用户登陆密码都会 mad5(salt + pwd) 然后再将 md 之后的数据 hex 一下. 这个工具类,就是实现此效果的. /* * */ package com.zuidaim

JAVA对象任意深度克隆clone工具类分享

原文:JAVA对象任意深度克隆clone工具类分享 源代码下载地址:http://www.zuidaima.com/share/1550463408114688.htm package com.zuidaima.n_app.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import jav

Java导出防止小数显示不全工具类

1.说明 在做项目的过程中,发现导出功能中的数据显示不全,如"0.4",会显示成".4":"-0.8"会显示成"-.8" 现在,通过以下Java工具类保证导出的数据(特别是小数)显示全 2.Java工具类 /** * @Title:DecimalPoint.java * @Package:com.you.model * @Description:解决导出时小数前的"0"被去掉的问题 * @Author: 游

Java获取时间 时间计算 转换时间工具类

Java获取时间 时间计算 转换时间工具类 JAVA日期工具类 package com.mh.util; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * 时间日期转换工具类 */ public class DateTimeUtil { /** *

java读写文件(可当工具类保存。解决乱码)

//读文件 public static String ReadFile(String path) { File file = new File(path); BufferedReader reader = null; String laststr = ""; try { reader = new BufferedReader(new FileReader(file)); String tempString = null; while ((tempString = reader.read

Java.util.zip 压缩与解压缩工具类

Java.util.zip 提供用于读写标准 ZIP 和 GZIP 文件格式的类. 还包括使用 DEFLATE 压缩算法(用于 ZIP 和 GZIP 文件格式)对数据进行压缩和解压缩的类. 依赖 Jdk 编写该工具类,不依赖任何第三方 jar,随用随取,实现功能大体如下: 1.目录级别递归压缩与解压缩 zip: 2.单文件压缩和解压缩 zip : import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipIn

java分页的实现(后台工具类和前台jsp页面)

1.首先,新建一个类Page.java 1 public class Page implements Serializable { 2 private static final long serialVersionUID = -3198048449643774660L; 3 private int pageNow = 1; // 当前页数 4 private int pageSize = 10; // 每页显示记录的条数 5 private int totalCount; // 总记录条数 6

Java数组操作利器:Arrays工具类

java.util.Arrays提供大量的工具方法来操作数组,这些方法全是静态方法. 1 便捷创建List public static <T> List<T> asList(T... a) 返回一个受指定数组支持的固定大小的列表. public static <T> List<T> asList(T... a) { return new ArrayList<>(a); } 典型用法:List<String> stooges = Arr

Java基础---泛型、集合框架工具类:collections和Arrays

第一讲     泛型(Generic) 一.概述 1.JDK1.5版本以后出现的新特性.用于解决安全问题,是一个类型安全机制. 2.JDK1.5的集合类希望在定义集合时,明确表明你要向集合中装入那种类型的数据,无法加入指定类型以外的数据. 3.泛型是提供给javac编译器使用的可以限定集合中的输入类型说明的集合时,会去掉“类型”信息,使程序运行效率不受影响,对参数化的泛型类型,getClass()方法的返回值和原始类型完全一样. 4.由于编译生成的字节码会去掉泛型的类型信息,只要能跳过编译器,就