【网络工具】小平头PingTow网络IP导入检测工具软件开发源代码分享

654 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情 >>

一、软件功能与截图

做一款面向网络运维人员的IP通断状态检测小软件,核心是通过运行Ping命令拿到IP网络状态,目前有一个简陋UI界面,支持批量导入Excel格式的IP数据,然后自动检测网络通断。软件本体是jar包,可以通过exe4j工具打包为Windows PC机下运行的EXE程序,也可以运行到Linux操作系统。 该文档不定时更新。 未来打算支持功能点有:

  • 将支持单个IP做网络通断测试,即每一个IP旁边放置一个按钮
  • 将支持将IP检测结果表格导出为PDF或图片,方便分享数据
  • 将支持自动不定时对IP地址做检测,动态更新检测结果
  • 计划增加多线程,缩短响应时间

多Excel文档批量导入IP信息

1.文件支持选择多个Excel文档

在这里插入图片描述

2.Excel文件的表头要求

表头名字随便取,顺序必须与截图保持一致在这里插入图片描述

IP信息Ping结果列表展示

解析结果

二、源码分享与设计

Maven-Pom依赖

<!--  POI Excel Jar-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

Excel数据导入-基于POI包

  • 负责解析Excel数据为Java对象PingInfoInputDTO的方法类:MyExcelServiceImpl
public class MyExcelServiceImpl implements  EasyExcelService {
    @Override
    public List<PingInfoInputDTO> readExcel(File file) {
        try {
//            HSSFWorkbook workBook = new HSSFWorkbook(new FileInputStream(new File(file.getAbsolutePath())));
            HSSFWorkbook workBook = new HSSFWorkbook(new FileInputStream(file));
            //页
            int sheetNum = workBook.getNumberOfSheets();
            DataFormatter cellDataFormatter = new DataFormatter();
            List<PingInfoInputDTO> pingInfoList = new ArrayList<>(300);
            for( int i=0; i<sheetNum; i++ ){
                HSSFSheet sheetData =  workBook.getSheetAt(i);
                //行:每行数据对应一个对象
                int lastRowNum = sheetData.getLastRowNum();
                for( int j=1; j<lastRowNum ; j++){
                    //跳过首行表头,j=1
                    HSSFRow rowData = sheetData.getRow(j);
                    //单元格
                    short lastCellNum = rowData.getLastCellNum();
                    PingInfoInputDTO pingDTO = new PingInfoInputDTO();
                    int k = 0;
                    //IpNo数据编号
                    pingDTO.setIpNo(cellDataFormatter.formatCellValue(rowData.getCell(k++)));
                    //IP地址别名
                    pingDTO.setIpAliasName(cellDataFormatter.formatCellValue(rowData.getCell(k++)));
                    //IP地址
                    pingDTO.setIpAddress(cellDataFormatter.formatCellValue(rowData.getCell(k++)));
                    //Ping超时
                    pingDTO.setPingTimeout(cellDataFormatter.formatCellValue(rowData.getCell(k++)));
                    //最大Ping次数
                    pingDTO.setPingMaxCount(cellDataFormatter.formatCellValue(rowData.getCell(k++)));

                    pingInfoList.add(pingDTO);
                }
            }
            workBook.close();
            return pingInfoList;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new ArrayList<>();
        } catch (IOException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }

    }
}
  • 接口层 EasyExcelService.java
public interface EasyExcelService {
   List<PingInfoInputDTO> readExcel(File file);
}
  • POJO:PingInfoInputDTO
public class PingInfoInputDTO {

    //数据标识和序号
    private String ipNo;
    //Ping 目标地址
    private String ipAddress;
    //Ping地址别名
    private String ipAliasName;
    //Ping超时设置,默认1000ms
    private String pingTimeout;
    //Ping次数上限
    private String pingMaxCount;


    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    public String getPingTimeout() {
        return pingTimeout;
    }

    public void setPingTimeout(String pingTimeout) {
        this.pingTimeout = pingTimeout;
    }

    public String getPingMaxCount() {
        return pingMaxCount;
    }

    public void setPingMaxCount(String pingMaxCount) {
        this.pingMaxCount = pingMaxCount;
    }

    public String getIpAliasName() {
        return ipAliasName;
    }

    public void setIpAliasName(String ipAliasName) {
        this.ipAliasName = ipAliasName;
    }

    public String getIpNo() {
        return ipNo;
    }

    public void setIpNo(String ipNo) {
        this.ipNo = ipNo;
    }

    @Override
    public String toString() {
        return "PingInfoInputDTO{" +
                "ipNo='" + ipNo + '\'' +
                ", ipAddress='" + ipAddress + '\'' +
                ", ipAliasName='" + ipAliasName + '\'' +
                ", pingTimeout='" + pingTimeout + '\'' +
                ", pingMaxCount='" + pingMaxCount + '\'' +
                '}';
    }
}

IP地址Ping方法-

  • 实现类
public class PingServiceImpl implements PingService {


    public PingInfoOutputDTO ping(PingInfoInputDTO infoInputDTO) {
        PingInfoOutputDTO outputDTO = new PingInfoOutputDTO();
        outputDTO.setInputDTO(infoInputDTO);
        outputDTO.setTargetIp(infoInputDTO.getIpAddress());

        BufferedReader in = null;
        String pingCommand = null;
        Runtime r = Runtime.getRuntime();
        String osName = System.getProperty("os.name");
        if(osName.contains("Windows")){
            //Windows Style: ping www.baidu.com -n 3
            pingCommand = "ping " + infoInputDTO.getIpAddress() + " -n " + infoInputDTO.getPingMaxCount();
        }else{
            //Linux Style: ping -c 10 www.baidu.com
            pingCommand = "ping " + " -c " + infoInputDTO.getPingMaxCount() + "  " +  infoInputDTO.getIpAddress();
        }
        try {
            //Process
            System.out.println("To process command:" + pingCommand);
            Process p = r.exec(pingCommand);
            if (p == null) {
                outputDTO.setPingStatus(false);
                outputDTO.setPingRes("System Error!");
                outputDTO.setPingResponseTime(new Date());
            }
            //Check
            in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            int connectedCount = 0;
            String line = null;
            while ((line = in.readLine()) != null) {
                if(osName.contains("Windows")){
                    if(line.contains("TTL=")){
                        connectedCount++;
                    }
                }else{
                    if(line.contains("ttl=")){
                        connectedCount++;
                    }
                }
            }
            System.out.println("IP: " + infoInputDTO.getIpAddress() +  ",Ping Success Count:" +connectedCount);
            if(connectedCount >= 1){
                outputDTO.setPingResponseTime(new Date());
                outputDTO.setPingStatus(true);
                outputDTO.setPingRes("连通");
            }else{
                outputDTO.setPingResponseTime(new Date());
                outputDTO.setPingStatus(false);
                outputDTO.setPingRes("故障");
            }
            return outputDTO;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}
  • 接口定义
public interface PingService {

    PingInfoOutputDTO ping(PingInfoInputDTO infoInputDTO);

}

GUI界面-Java Swing-程序入口

本类同时也是程序的入口

public class FrameUITest {


    public static void main(String[] args) {

        //校验通过的文件类型
        List<File> VALID_FILE_LIST = new ArrayList<File>(6);
        //校验失败的文件类型
        List<File> INVALID_FILE_LIST = new ArrayList<File>(6);

        int frameWidth = 700;
        int frameHeight = 500;

        SimpleDateFormat simpleDateFormat =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String appTitle = "小平头网络IP地址通讯状态检测工具PingTow2.0";
        //统一设置字体
        InitGlobalFont(new Font("alias", Font.PLAIN, 18));
        JFrame frame = new JFrame(appTitle);
        frame.setSize(frameWidth, frameHeight);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        // 创建内容面板,指定使用 流式布局
        JPanel panel = new JPanel(new FlowLayout());
//        JPanel panel = new JPanel(new GridLayout(3,1));

        //显示用户所选文件名称
        JLabel fileNameLabel = new JLabel();
        fileNameLabel.setText("您选择的文件是:_______");
        fileNameLabel.setFont(new Font(null, Font.PLAIN, 15));
        fileNameLabel.setSize(300,80);
        panel.add(fileNameLabel);

        //用于文件上传的按钮
        JButton fileUploadBtn = new JButton("       上传Excel文件      ");
        fileUploadBtn.setSize(400,80);

        fileUploadBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //点击按钮后打开文本框
                JFileChooser chooser = new JFileChooser();
                //开启文件多选
                chooser.setMultiSelectionEnabled(true);
                /** 过滤文件类型 * */
                FileNameExtensionFilter filter = new FileNameExtensionFilter("","xls");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(fileUploadBtn);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    //选择的文件
                    File[] fileArr = chooser.getSelectedFiles();
                    if (fileArr == null || fileArr.length == 0) {
                        JOptionPane.showMessageDialog(new JDialog(), "错误!请正确选择文件.");
                        return;
                    }
                    //循环校验所选文件的类型
                    StringBuilder fileNameBuilder = new StringBuilder();
                    for (File item : fileArr) {
                        //判断是否有文件为xls或xlsx
                        String fileName = item.getName();
                        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
                        if ((prefix.equals("xls") || prefix.equals("xlsx"))) {
                            VALID_FILE_LIST.add(item);
                            fileNameBuilder.append(fileName);
                        } else {
                            INVALID_FILE_LIST.add(item);
                        }
                    }
                    //更新UI界面用户所选文件
                    fileNameLabel.setText("您所选文件是:" + fileNameBuilder.toString());
                    System.out.println("有效文件:" + VALID_FILE_LIST + ",无效文件:" + INVALID_FILE_LIST);

                    //检测IP
                    //Excel File -> PingInfoInputDTO
                    List<PingInfoInputDTO> pingInfoList = new ArrayList<>(100);
                    EasyExcelService excelService = new MyExcelServiceImpl();
                    if(CollectionUtils.isNotEmpty(VALID_FILE_LIST) && !CollectionUtils.sizeIsEmpty(VALID_FILE_LIST)){
                        for (File file : VALID_FILE_LIST) {
                            List<PingInfoInputDTO> list = excelService.readExcel(file);
                            pingInfoList.addAll(list);
                        }
                    }
                    //检测IP
                    List<PingInfoOutputDTO> outPutList = new ArrayList<>(100);
                    PingService pingService = new PingServiceImpl();
                    if(CollectionUtils.isNotEmpty(pingInfoList) && !CollectionUtils.sizeIsEmpty(pingInfoList)){
                        for (PingInfoInputDTO item : pingInfoList) {
                            PingInfoOutputDTO out = pingService.ping(item);
                            outPutList.add(out);
                        }
                    }
                    //放一个列表展示解析结果
                       //转化为二维数组
                    String[][] tableData = new String[outPutList.size()][5];
                    int i=0;
                    for (PingInfoOutputDTO item : outPutList) {
                        PingInfoInputDTO inputDTO = item.getInputDTO();
                        tableData[i][0] = inputDTO.getIpNo();
                        tableData[i][1] = inputDTO.getIpAddress();
                        tableData[i][2] = inputDTO.getIpAliasName();
                        tableData[i][3] = item.getPingRes();
                        tableData[i][4] = simpleDateFormat.format(item.getPingResponseTime());
                        i++;
                    }

                    Object[] columnNames = {"序号", "   IP地址   ","    IP简称    ", " 网络状态  ", "   操作时间   "};
                    // 创建一个表格,指定 所有行数据 和 表头
                    JTable table = new JTable(tableData, columnNames);
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                    table.setForeground(new Color(100,200,80));
                    table.setShowGrid(true);
                    table.setRowHeight(40);
                    table.setPreferredScrollableViewportSize(new Dimension((int)0.8*frameWidth,(int)0.8*frameHeight));


                    // 把 表头 添加到容器顶部(使用普通的中间容器添加表格时,表头 和 内容 需要分开添加)
                    panel.add(table.getTableHeader(), BorderLayout.NORTH);
                    // 把 表格内容 添加到容器中心
                    panel.add(table, BorderLayout.CENTER);

                }
            }
        });
        panel.add(fileUploadBtn);


        frame.setContentPane(panel);

        frame.setVisible(true);
    }

    /**
     * 统一设置字体,父界面设置之后,所有由父界面进入的子界面都不需要再次设置字体
     */
    private static void InitGlobalFont(Font font) {
        FontUIResource fontRes = new FontUIResource(font);
        for (Enumeration<Object> keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
            Object key = keys.nextElement();
            Object value = UIManager.get(key);
            if (value instanceof FontUIResource) {
                UIManager.put(key, fontRes);
            }
        }
    }
}