[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");
	}
[root@xxxx ~]# 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);
	}
[root@xxxx ~]# 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


转载于:https://my.oschina.net/tangcoffee/blog/330223

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值