【运维开发】分享一个自动检测设备是否在线的脚本

211 阅读2分钟

为了方便运维工作,写了一个自动检测设备是否在线的脚本。

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class PingIPtoWX {
    public static void main(String[] args) throws IOException {
        Workbook workbook = null;
        workbook = WorkbookFactory.create(new File("ip.xlsx"));
//        assert workbook != null;
        Sheet sheet = workbook.getSheetAt(0);
        workbook.close();
//        for (Row row : sheet) 不能用增强for,需要跳过第一行表头
//        创建文件名
//        Date date = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//        String fileName = dateFormat.format(date) + "unreachable.txt";

        List<String> unreachable = new ArrayList<>();
        int lostCount = 0;
        for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
            Row row = sheet.getRow(i);

            // 跳过表头
            if (i == 0) {
                continue;
            }
            String ip = row.getCell(0).getStringCellValue();
            String hostname = row.getCell(1).getStringCellValue();
            boolean reachable = false;
            try {
                reachable = InetAddress.getByName(ip).isReachable(3000);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (!reachable) {
//                BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\Administrator\Desktop\PingIP\src\main\resources\" + fileName, true));
//                writer.write(ip + " " + hostname + "网络不通或响应差");
//                writer.newLine();
//                writer.close();

                unreachable.add(ip + "(" + hostname + ")");
                lostCount++;
            }
        }
        if (lostCount == 0){
            String content = "所有设备均可访问";
            String webhookUrl = "<your_webhook_url>";
            String message = "{"msgtype":"text","text":{"content":""+ content + ""}}";
            sendMessage(webhookUrl, message);
        }else {
            String content = "以下设备网络不通或响应差:" + unreachable;
            String message = "{"msgtype":"text","text":{"content":""+ content + ""}}";
            String webhookUrl = "<your_webhook_url>";
            sendMessage(webhookUrl, message);
        }
    }

    private static void sendMessage(String webhookUrl, String message) throws IOException {
        URL url = new URL(webhookUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStream os = conn.getOutputStream();
        os.write(message.getBytes(StandardCharsets.UTF_8));
        os.close();
        conn.getInputStream();
    }
}

由于是maven项目,打包的时候要记得指定主类和引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xiexinghuang</groupId>
    <artifactId>PingIPtoWX</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <packaging>jar</packaging>

    <build>
        <finalName>${project.artifactId}</finalName><!--修改编译出来的jar包名,仅为{artifactId}.jar-->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <!-- get all project dependencies -->
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>PingIPtoWX</mainClass> <!-- 此处为主入口-->
                        </manifest>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <!-- bind to the packaging phase -->
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>

</project>

在linux中安装java环境

1.查看查看可安装的jdk版本

yum -y list java*

2.以安装jdk1.8为例

yum install -y java-1.8.0-openjdk-devel.x86_64

3.查看安装好的java版本

java -version

打包好后将jar包和ip.xlsx放在Linux中,用linux自带的crond定期功能,定时执行脚本

# 查看定时任务(list查看)
crontab -l 
# 也等于
cat /var/spool/cron/root

# sh脚本编写
# 注意一定要cd到java工作目录,cron默认运行路径在root(家目录)
cd ./java && java -jar PingIPtoWX-jar-with-dependencies.jar
# 修改相关文件权限以免
chmod 777 ***.sh
chmod 777 ***.xlsx

# 创建定时任务(edit编辑)
crontab -e
# 将cron任务添加到crontab(和java的cron有点区别,第一个*代表分钟,没有秒)
40 15 * * * /root/java/runjava.sh >> /root/java/log.txt 2>&1
# 如果sh脚本中没有先cd到java工作目录,这需要先cd过去
40 15 * * * cd /root/java && /root/java/runjava.sh >> /root/java/log.txt 2>&1

# 检查cron是否在运行
systemctl is-active crond
systemctl status crond

执行的效果如下

image.png

如果设计多个定时任务,建议在Java程序中加入定时功能,Quartz是一个很好的任务调度框架。

//  先写一个类,实现Job接口
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException{
    // 需要定期执行的业务代码
    }

// 调度器类
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

public class SchedulerAtDay {
    public static void main(String[] args) throws SchedulerException {
        // 获取调度器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // 创建作业
        JobDetail job = JobBuilder.newJob(TestJob.class)
                .withIdentity("job1", "group1")
                .build();

        // 创建触发器
        // 每天14:30执行
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .withSchedule(CronScheduleBuilder.cronSchedule("0 28 14 * * ?"))
                .build();
        

        // 将作业和触发器添加到调度器中
        scheduler.scheduleJob(job, trigger);

        // 启动调度器
        scheduler.start();
    }
}

注意cron的用法和Linux小有区别一下有两个生成器链接供参考

JavaCron-奇Q工具网

LinuxCrond-Cronitor