使用SSH连接linux服务器重启Tomcat服务

一、创建SSH连接linux服务器操作命令工具类

package test.common;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
 * SSH连接linux服务器操作命令工具类
 */
public class SSHUtil {

    private Channel channel;
    private Session session = null;

    public SSHUtil(final String ipAddress, final String username, final String password) throws Exception {
        JSch jsch = new JSch();
        this.session = jsch.getSession(username, ipAddress, 22);
        this.session.setPassword(password);
        this.session.setConfig("StrictHostKeyChecking", "no");
        this.session.setTimeout(60000);
        this.session.connect();
        this.channel = this.session.openChannel("shell");
        this.channel.connect(30000);
    }

    /**
     * 执行操作命令
     * @param cmd 命令
     * @return
     * @throws Exception
     */
    public String runShell(String cmd) throws Exception {
        String temp = null;

        InputStream instream = null;
        OutputStream outstream = null;
        try {
            instream = this.channel.getInputStream();
            outstream = this.channel.getOutputStream();
            outstream.write(cmd.getBytes());
            outstream.flush();
            TimeUnit.SECONDS.sleep(2);
            if (instream.available() > 0) {
                byte[] data = new byte[instream.available()];
                int nLen = instream.read(data);
                if (nLen < 0) {
                    throw new Exception("network error.");
                }
                temp = new String(data, 0, nLen, "UTF-8");
            }
        }  finally {
            outstream.close();
            instream.close();
        }
        return temp;
    }

    /**
     * 执行相关的命令可返回执行结果
     * @param command 命令
     * @return
     * @throws Exception
     */
    public String execCmd(String command) throws Exception{

        BufferedReader reader = null;
        Channel channel = null;
        StringBuffer sb=new StringBuffer("");

        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        channel.connect();
        InputStream in = channel.getInputStream();
        reader = new BufferedReader(new InputStreamReader(in,
                Charset.forName("utf-8")));
        String buf = null;
        while ((buf = reader.readLine()) != null) {
           sb.append(buf);
        }
        reader.close();
        return sb.toString();
    }

    /**
     * 关闭SSH连接
     */
    public void close() throws Exception{
        this.channel.disconnect();
        this.session.disconnect();
    }

}

二、创建操作Tomcat重启工具类

/**
 * 
 */
package test.common;

import java.io.IOException;
import org.apache.log4j.Logger;


/**
 * tomcat重启操作类
 */
public class TomcatUtil {

    private static Logger logger = Logger.getLogger(TomcatUtil.class);


    //软件安装目录
    private  String tomcatDir;

    //重试次数
    private  int retryTime;

    //重启关闭线程等待时间
    private  String  waitingTime;


    public TomcatUtil(String tomcatDir, int retryTime, String waitingTime) {
        this.tomcatDir = tomcatDir;
        this.retryTime = retryTime;
        this.waitingTime = waitingTime;
    }

    public static void main(String[] args) {
        SSHUtil sshUtil =null;
        TomcatUtil  tomcatUtil =null;

        try {
            sshUtil = new SSHUtil("127.0.0.1", "root", "mima");
            tomcatUtil =new TomcatUtil("/usr/local/tomcat/",10, "10000");
            tomcatUtil.restartTomcat(sshUtil);
            sshUtil.close();
            sshUtil =null;
        } catch (Exception e) {
            e.printStackTrace();
            if(sshUtil != null){
                try {
                    sshUtil.close();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                sshUtil =null;
            }

        }

    }

    /**
     * 重启Tomcat
     * @param runtime
     * @return
     * @throws IOException
     */
    public  boolean restartTomcat(SSHUtil sshUtil) throws Exception{
        //结束tomcat进程
        logger.info("开始执行重启Tomcat...");
        for (int i = 0; i < retryTime; i++) {
            logger.info("执行关闭Tomcat第"+(i+1)+"次...");
            if(isExistTomcatProcess(sshUtil)) {
                try {
                    //强制结束进程
                    logger.info("kill命令强制结束进程关闭Tomcat...");
                    killTomcatBySoft(sshUtil);
                    logger.info("kill命令关闭Tomcat后等待"+waitingTime+"毫秒。。。");
                    Thread.sleep(Integer.valueOf(waitingTime));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    logger.info("执行关闭Tomcat第"+(i+1)+"次...异常:",e);
                }
            }else {
                logger.info("未发现需要执行关闭Tomcat第"+(i+1)+"次...");
                break;
            }
        }
        logger.info("执行关闭Tomcat完成!");

        //启动tomcat
        for (int i = 0; i < retryTime; i++) {
            logger.info("执行启动Tomcat第"+(i+1)+"次...");
            if(!isExistTomcatProcess(sshUtil)) {
                //调用tomcat自身脚本重启程序
                startupTomcat(sshUtil);
                try {
                    logger.info("启动Tomcat后等待"+waitingTime+"毫秒。。。");
                    Thread.sleep(Integer.valueOf(waitingTime));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    logger.info("执行启动Tomcat第"+(i+1)+"次...异常:",e);
                }
            }else {
                logger.info("执行启动Tomcat第"+(i+1)+"次...");
                break;
            }
        }

        if(isExistTomcatProcess(sshUtil)) {
            logger.info("重启tomcat成功!");
            return true;
        }else {
            logger.info("重启tomcat失败!");
            return false;
        }

    }

    /**
     * 判断是否含有tomcat进程
     * @param runtime
     * @return
     * @throws IOException
     */
    public  boolean isExistTomcatProcess(SSHUtil sshUtil) throws Exception {
        String command = "ps -ef | grep "+this.tomcatDir .split("/")[this.tomcatDir .split("/").length-1]+"/ | grep -v grep | awk '{print $2}';";
        return isExistProcess(sshUtil, command);
    }



    /**
     * 判断当前进程中是否含有program
     * @param runtime
     * @param program
     * @return
     * @throws IOException
     */
    public  boolean isExistProcess(SSHUtil sshUtil, String command) throws Exception {
        boolean isExistTomcatProcess = false;
         String res = sshUtil.execCmd(command);
        if(res.length() > 0) {
            isExistTomcatProcess = true;
        }
        logger.info("判断是否含有tomcat进程:"+isExistTomcatProcess);
        return isExistTomcatProcess;
    }



    /**
     * 启动Tomcat
     * @param runtime
     * @throws IOException
     */
    public  void startupTomcat(SSHUtil sshUtil) throws Exception {
        logger.info("执行启动Tomcat脚本程序:"+this.tomcatDir  + "bin/startup.sh");
        sshUtil.runShell(tomcatDir + "bin/startup.sh\n");
    }


    /**
     * 强制kill结束Tomcat进程
     * @param runtime
     * @throws IOException
     */
    public  void killTomcatBySoft(SSHUtil sshUtil) throws Exception {
        String command = "ps -ef | grep "+this.tomcatDir .split("/")[this.tomcatDir .split("/").length-1]+"/ | grep -v grep | awk '{print $2}';";
        String res = sshUtil.execCmd(command);
        if(res.length() > 0) {
            sshUtil.execCmd("kill -9 "+res);
        }
        logger.info("执行kill 命令,关闭Tomcat");
    }

    public String getTomcatDir() {
        return tomcatDir;
    }

    public void setTomcatDir(String tomcatDir) {
        this.tomcatDir = tomcatDir;
    }

    public int getRetryTime() {
        return retryTime;
    }

    public void setRetryTime(int retryTime) {
        this.retryTime = retryTime;
    }

    public String getWaitingTime() {
        return waitingTime;
    }

    public void setWaitingTime(String waitingTime) {
        this.waitingTime = waitingTime;
    }



}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值