Java 远程服务启停demo

gradle依赖

implementation 'com.jcraft:jsch:0.1.55'
public String startOrStopService(Map map) {
        String host = "localhost";
        String username = "root";
        String password = "root";
        String sudoPassword = "root";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(username, host, 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            String sudoCommand = "";
            if (map.get("serviceName") != null && map.get("course") != null) {

                String serviceName = String.valueOf(map.get("serviceName"));
                String course = String.valueOf(map.get("course"));

                switch (serviceName) {
                    case "nginx":
                        sudoCommand = "sudo -S systemctl " + (course.equals("1") ? "start" : "stop") + " nginx";
                        break;
                    case "mongodb":
                        sudoCommand = "sudo -S systemctl " + (course.equals("1") ? "start" : "stop") + " mongodb";
                        break;
                    case "kafka":
                        sudoCommand = "sudo -S systemctl " + (course.equals("1") ? "start" : "stop") + " kafka";
                    case "minio":
                        // 需要走docker容器启动
                        sudoCommand = "sudo -S systemctl " + (course.equals("1") ? "start" : "stop") + " minio";
                    default:
                        // Handle other service names if needed
                        break;
                }

            }

            String fullCommand = sudoCommand + "\n";

            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(fullCommand);

            // 使用输入流向 channel 写入密码
            InputStream in = channelExec.getInputStream();
            OutputStream out = channelExec.getOutputStream();

            channelExec.connect();

            // 如果需要输入sudo密码,可以将密码写入输出流
            out.write((sudoPassword + "\n").getBytes());
            out.flush();

            // 读取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // 关闭流和连接
            out.close();
            in.close();
            reader.close();
            channelExec.disconnect();
            session.disconnect();
            if (map.get("course") != null && String.valueOf(map.get("course")).equals("1")) {
                return "1";
            } else {
                return "0";
            }
        } catch (Exception e) {
            LOG.error("执行命令失败", e);
            return "fail";
        }

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容