zoukankan      html  css  js  c++  java
  • java基础/java调用shell命令和脚本

    一。项目需求:

    从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书。

    问题:linux服务器启动该服务,不能关闭。一旦关闭,服务即停止。

    解决方案:java调用shell命令,利用spring容器启动即执行方案。

    参考博文:http://zohan.iteye.com/blog/1709136

    项目结构:

    原码:

    1。RuntimeUtils.java

     1 package com.csvalue.common;
     2 
     3 import org.springframework.util.StringUtils;
     4 
     5 import java.io.File;
     6 import java.io.IOException;
     7 
     8 /*
     9 * java调用sheet脚本工具类
    10 * */
    11 public class RuntimeUtils {
    12     public static Process exec(String command, String envp, String dir)
    13             throws IOException {
    14         String regex = "\s+";
    15         String args[] = null;
    16         String envps[] = null;
    17         if (!StringUtils.isEmpty(command)) {
    18             args = command.split(regex);
    19         }
    20         if (!StringUtils.isEmpty(envp)) {
    21             envps = envp.split(regex);
    22         }
    23         return Runtime.getRuntime().exec(args, envps, new File(dir));
    24     }
    25 }
    View Code

    2。p10Server.java

     1 package com.csvalue.service.impl;
     2 
     3 import com.csvalue.common.RuntimeUtils;
     4 import org.slf4j.LoggerFactory;
     5 import org.springframework.stereotype.Component;
     6 import org.springframework.stereotype.Service;
     7 
     8 import javax.annotation.PostConstruct;
     9 
    10 /*
    11 * Spring容器启动即启动sh脚本文件
    12 * */
    13 @Service
    14 public class P10Server {
    15     final org.slf4j.Logger log = LoggerFactory.getLogger(getClass());
    16     @PostConstruct
    17     public void init(){
    18         System.out.println("启动p10服务:init....");
    19         String command = "sh startup.sh";
    20         String dir=RuntimeUtils.class.getResource("/").getPath()+"KTServer";
    21         System.out.println(dir);
    22         try {
    23             RuntimeUtils.exec(command, null, dir);
    24             //Process process = RuntimeUtils.exec(command, null, dir);
    25             //int i = process.waitFor();
    26            // System.exit(i);
    27         }catch (Exception e){
    28             log.error("启动p10异常:"+e.getMessage());
    29         }
    30 
    31     }
    32 }
    View Code

    注意:p10Server.java中注释掉的部分。若开启,则服务一直启动不起来!!!

  • 相关阅读:
    HTML5存储
    HTML5全局属性和事件
    HTML5媒体(音频/视频)
    HTML5标签canvas制作动画
    HTML5标签canvas图像处理
    开发kendo-ui弹窗组件
    HTML5标签canvas制作平面图
    javascript匿名函数
    Javascript富文本编辑器
    快速排序算法(python版本)
  • 原文地址:https://www.cnblogs.com/kaixinyufeng/p/9701140.html
Copyright © 2011-2022 走看看