ping或掃描端口的Java工具類

jopen 10年前發布 | 42K 次閱讀 Java工具類 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;
}

}</pre>

 

配置掃描

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

 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!