当前位置:   article > 正文

cmd中根据启动命令查找jar进程的pid,cmd中结束指定jar进程_根据pid查jar包

根据pid查jar包

一、获取pid

wmic process where "name like '%java%' and commandline like '%[启动命令行中写的jar包名称,确保唯一]%' " get processid
  • 1

二、根据pid结束进程(若大家有其他方式获取pid,可跳过第一步)

"taskkill /pid " + pid + "  -t -f"
  • 1

此处贴我的springboot中启动、结束jar及其他应用(nginx等)方法

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.Executors.newFixedThreadPool;
public class Service {

    private List<String> processServer = new ArrayList<String>() {{
        add("nginx");
        add("redis");
        add("mysql");
    }};
    //启动服务命令
    private final static Map<String, String> startServerCmd = new HashMap<String, String>() {
        {
            put("nginx", "start nginx.bat");
            put("dbWeb", " start dbWeb.bat ");
            put("redis", " start redis.bat ");
            put("mysql", " start mysql.bat ");
            put("eureka", " start eureka.bat ");
            put("clear", " start clear.bat ");
            put("inte", " start inte.bat ");
            put("jdbc", " start jdbc.bat ");
            put("sys", " start sys.bat ");
        }
    };
    //停止服务命令
    private final static Map<String, String> stopServerCmd = new HashMap<String, String>() {
        {
            put("nginx", "start nginx-stop.bat");
            put("redis", " start redis-stop.bat ");
            put("mysql", " start mysql-stop.bat ");
        }
    };
    //检查服务有无开启
    private final static Map<String, String> examineServerCmd = new HashMap<String, String>() {
        {
            put("nginx", "nginx.exe");
            put("redis", "redis-server.exe");
            put("mysql", "mysqld.exe");

            put("dbWeb", "dbWeb.jar");
            put("eureka", "eureka_server.jar");
            put("clear", "data_clear_server.jar");
            put("inte", "integration.jar");
            put("jdbc", "jdbc_server.jar");
            put("sys", "system-options.jar");
        }
    };

    //检查服务有无开启
    public boolean examineServer(String serverName) {
        String cmd = examineServerCmd.get(serverName);
        if (processServer.contains(serverName)) {
            return findProcess(cmd);
        } else {
            return findJar(cmd);
        }
    }

    //启动服务
    public void startServer(String serverName) {
        String cmd = startServerCmd.get(serverName);
        try {
            executeCmd(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //停止服务
    public void stopServer(String serverName) {
        String server = examineServerCmd.get(serverName);
        if (processServer.contains(serverName)) {
            //结束进程
            String cmd = stopServerCmd.get(serverName);
            try {
                executeCmd(cmd);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //结束jar服务
            List<Integer> jarPid = findJarPid(server);
            for (int pid : jarPid) {
                dieByPid(pid);
            }
        }
    }

    //判断进程是否开启
    private static boolean findProcess(String processName) {
        BufferedReader bufferedReader = null;
        try {
            String cmd = "tasklist -fi " + '"' + "imagename eq " + processName + '"';
            Process proc = Runtime.getRuntime().exec(cmd);
            bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(processName)) {
                    return true;
                }
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    //判断jar是否启动
    private static boolean findJar(String jarName) {
        BufferedReader bufferedReader = null;
        try {
            String cmd = "wmic process where " + '"' +
                    "name like '%java%' and commandline like '%" + jarName + "%' " + '"' + " get processid,commandline ";
            Process proc = Runtime.getRuntime().exec(cmd);
            bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.contains(jarName)) {
                    return true;
                }
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception ex) {
                }
            }
        }
    }

    //获取jar pid
    private static List<Integer> findJarPid(String jarName) {
        BufferedReader bufferedReader = null;
        List<Integer> pid = new ArrayList<>();
        try {
            String cmd = "wmic process where " + '"' +
                    "name like '%java%' and commandline like '%" + jarName + "%' " + '"' + " get processid";
            Process proc = Runtime.getRuntime().exec(cmd);
            bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                if (!line.contains("ProcessId") && !"".equals(line)) {
                    line = line.replace(" ", "");
                    pid.add(Integer.parseInt(line));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception ex) {
                }
            }
        }
        return pid;
    }

    //终止pid
    private static void dieByPid(Integer pid) {
        String cmd = "taskkill /pid " + pid + "  -t -f";
        try {
            String executeCmd = executeCmd(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //打开配置文件
    private void openConf(String path) {
        String cmd = "notepad " + path;
        try {
            executeCmd(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String workPath = System.getProperty("user.dir")+"/../";//当前根目录
    private String applicationPath = workPath + "/application/";//jar初始配置目录
    private List<String> txtShow = new ArrayList<String>() {{
        add("nginx");
        add("mysql");
        add("redis");
    }};//需要用记事本打开的方法

    private List<String> jarConfName = new ArrayList<String>() {{
        add("application.properties");
        add("application.yml");
    }};//jar的配置文件名称
    private Map<String,String> outherConfName = new HashMap<String, String>(){{
        put("nginx","/nginx/conf/nginx.conf");
        put("redis","/redis/redis.windows.conf");
        put("mysql","/mysql/my.ini");
    }};//其他配置文件名称

    //打开配置文件用线程
    private ExecutorService exec = newFixedThreadPool(15);

    //检测缺失的配置文件,将文件进行复制
    List<String> deficiencyConfFile(String serverName) {
        List<String> confNameList = new ArrayList<>();
        if (!txtShow.contains(serverName)) {
            //jar服务,检查application文件数目
            String path = applicationPath + serverName;
            File file = new File(path);
            File[] sourceFiles = file.listFiles(item -> (item.isFile() && jarConfName.contains(item.getName())));
            if (sourceFiles == null) {
                System.out.println("未找到配置文件");
                confNameList.add("error");
                return confNameList;
            }
            List<File> sourcefileList = Arrays.asList(sourceFiles);
            //获取完初始的配置文件后,去jar目录对比配置文件数量

            //网站后台程序,目录不同
            path = "dbWeb".equals(serverName) ? workPath + "/" + serverName : workPath + "/jar/" + serverName;
            file = new File(path);

            File[] targetFiles = file.listFiles(item -> (item.isFile() && jarConfName.contains(item.getName())));//jar中的配置文件数
            if (targetFiles != null) {
                List<String> targetConfList = new ArrayList<>();
                for (File file1 : targetFiles) {
                    targetConfList.add(file1.getName());
                }

                //jar服务的目录下已有配置文件,移除已有的
                sourcefileList = new ArrayList<>(sourcefileList);
                for (int i = sourcefileList.size() - 1; i >= 0; i--) {
                    if (targetConfList.contains(sourcefileList.get(i).getName())) {
                        sourcefileList.remove(i);
                    }
                }
                for (File file1 : sourcefileList) {
                    String outPath = path + "/" + file1.getName();
                    Path sourcePath = Paths.get(file1.getPath());
                    Path outPath1 = Paths.get(outPath);
                    try {
                        Files.copy(sourcePath, outPath1);
                        confNameList.add(file1.getName());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (confNameList.size() > 0) {
                System.out.println(serverName + "服务配置文件初始化成功,共加载" + confNameList.size() + "个文件,其中包含: \n" + String.join("\n", confNameList));
                }
            }
        }
        return confNameList;
    }

    void openJarConf(String serverName) {
        String path = "dbWeb".equals(serverName) ? workPath + "/" + serverName : workPath + "/jar/" + serverName;
        File file = new File(path);
        File[] targetFiles = file.listFiles(item -> (item.isFile() && jarConfName.contains(item.getName())));//jar中的配置文件数

        if (targetFiles != null) {
            for (File file1 : targetFiles) {
                exec.execute(() -> {
                    openConf(file1.getPath());
                });
            }
        } else {
            fileNotExit(path);
        }
        System.out.println(((ThreadPoolExecutor)exec).getActiveCount());
    }
    void openOutherConf(String serverName) {
        String path = workPath+outherConfName.get(serverName);
        File file = new File(path);
        if(!file.isFile()){
            fileNotExit(path);
            return;
        }
        exec.execute(()->{
            openConf(path);
        });
    }
    private void fileNotExit(String path){
    System.out.println("未找到配置文件,建议检查目录、文件名称("+path+")或重新安装以获取配置文件");
    }

    //windows执行cmd
    private static String executeCmd(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec("cmd /c " + command);
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
        String line;
        StringBuilder build = new StringBuilder();
        while ((line = br.readLine()) != null) {
            build.append(line);
        }
        return build.toString();
    }

    //linux执行cmd
    private static String executeLinuxCmd(String command) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
        String line = null;
        StringBuilder build = new StringBuilder();
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            build.append(line);
        }
        return build.toString();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/76334
推荐阅读
相关标签
  

闽ICP备14008679号