Shell 脚本 —— java 代码远程调用shell脚本重启 tomcat

个人博客网:https://wushaopei.github.io/    (你想要这里多有)

1、创建maven 工程

maven 依赖:

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.13.RELEASE</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/logutil/logutil -->

        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>

2、创建 RemoteShellExecutor. java  文件用于远程连接Linux 服务器

package com.webcode.cn;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.io.IOUtils;
import ch.ethz.ssh2.Connection;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;


public class RemoteShellExecutor {
    private Connection conn;
       /** 远程机器IP */
               private String ip;
       /** 用户名 */
               private String osUsername;
       /** 密码 */
               private String password;
       private String charset = Charset.defaultCharset().toString();

               private static final int TIME_OUT = 1000 * 5 * 60;

               /**
         * 构造函数
         * @param ip
         * @param usr
         * @param pasword
         */
               public RemoteShellExecutor(String ip, String usr, String pasword) {
                   this.ip = ip;
                  this.osUsername = usr;
                  this.password = pasword;
              }


               /**
        * 登录
        * @return
        * @throws IOException
        */
               private boolean login() throws IOException {
                  conn = new Connection(ip);
                 conn.connect();
                  return conn.authenticateWithPassword(osUsername, password);
              }

               /**
        * 执行脚本
        *
       * @param cmds
        * @return
        * @throws Exception
        */
               public int exec(String cmds) throws Exception {
                  InputStream stdOut = null;
                  InputStream stdErr = null;
                  String outStr = "";
                  String outErr = "";
                  int ret = -1;
                  try {
                      if (login()) {
                              // Open a new {@link Session} on this connection
                              Session session = conn.openSession();
                          // Execute a command on the remote machine.
                              session.execCommand(cmds);

                              stdOut = new StreamGobbler(session.getStdout());
                              outStr = processStream(stdOut, charset);

                              stdErr = new StreamGobbler(session.getStderr());
                              outErr = processStream(stdErr, charset);

                              session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);

                              System.out.println("outStr=" + outStr);
                              System.out.println("outErr=" + outErr);

                              ret = session.getExitStatus();
                          } else {
                              throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
                          }
                      } finally {
                          if (conn != null) {
                                  conn.close();
                              }
                          IOUtils.closeQuietly(stdOut);
                          IOUtils.closeQuietly(stdErr);
                      }
                  return ret;
              }

               /**
        * @param in
        * @param charset
        * @return
        * @throws IOException
        * @throws UnsupportedEncodingException
        */
               private String processStream(InputStream in, String charset) throws Exception {
                  byte[] buf = new byte[1024];
                  StringBuilder sb = new StringBuilder();
                  while (in.read(buf) != -1) {
                          sb.append(new String(buf, charset));
                      }
                  return sb.toString();
              }

             public static void main(String args[]) throws Exception {
                 RemoteShellExecutor executor = new RemoteShellExecutor("192.168.2xx.118", "root", "15989xxxxxx***");
                 // 执行myTest.sh 参数为java Know dummy
                 System.out.println(executor.exec("/home/wenmin/kill-tomcat.sh"));
             }

}

3、在Linux  /home/wenmin 目录下创建 kill-tomcat.sh  脚本文件

#!/bin/bash

#kill tomcat pid

pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'`  #找到tomcat的PID号

echo "tomcat Id list :$pidlist"  //显示pid

kill -9 $pidlist  #杀掉改进程

echo "KILL $pidlist:" //提示进程以及被杀掉

echo "service stop success"

echo "start tomcat"

cd /opt/apache-tomcat-7.0.75

pwd

rm -rf work/*

cd bin

./startup.sh #;tail -f ../logs/catalina.out

4、执行 main  方法

J:folderJDK1.8injava -javaagent:J:P2CideaIU-2017.2.winlibidea_rt.jar=62052:J:P2CideaIU-2017.2.winin -Dfile.encoding=UTF-8 -classpath J:folderJDK1.8jrelibcharsets.jar;J:folderJDK1.8jrelibdeploy.jar;J:folderJDK1.8jrelibextaccess-bridge-64.jar;J:folderJDK1.8jrelibextcldrdata.jar;J:folderJDK1.8jrelibextdnsns.jar;J:folderJDK1.8jrelibextjaccess.jar;J:folderJDK1.8jrelibextjfxrt.jar;J:folderJDK1.8jrelibextlocaledata.jar;J:folderJDK1.8jrelibext
ashorn.jar;J:folderJDK1.8jrelibextsunec.jar;J:folderJDK1.8jrelibextsunjce_provider.jar;J:folderJDK1.8jrelibextsunmscapi.jar;J:folderJDK1.8jrelibextsunpkcs11.jar;J:folderJDK1.8jrelibextzipfs.jar;J:folderJDK1.8jrelibjavaws.jar;J:folderJDK1.8jrelibjce.jar;J:folderJDK1.8jrelibjfr.jar;J:folderJDK1.8jrelibjfxswt.jar;J:folderJDK1.8jrelibjsse.jar;J:folderJDK1.8jrelibmanagement-agent.jar;J:folderJDK1.8jrelibplugin.jar;J:folderJDK1.8jrelib
esources.jar;J:folderJDK1.8jrelib
t.jar;J:IDEA_Work_Spaceshell-java	argetclasses;C:Userswushaopei.m2
epositoryorgjvnethudsonganymed-ssh2uild210-hudson-1ganymed-ssh2-build210-hudson-1.jar;C:Userswushaopei.m2
epositorycommons-iocommons-io2.1commons-io-2.1.jar;C:Userswushaopei.m2
epositoryorgapachelogginglog4jlog4j-core2.11.1log4j-core-2.11.1.jar;C:Userswushaopei.m2
epositoryorgapachelogginglog4jlog4j-api2.11.1log4j-api-2.11.1.jar com.webcode.cn.RemoteShellExecutor
outStr=tomcat Id list :14141 //显示pid
KILL 14141: //提示进程以及被杀掉
service stop success
start tomcat
/opt/apache-tomcat-7.0.75
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Using CATALINA_BASE:   /opt/apache-tomcat-7.0.75
Using CATALINA_HOME:   /opt/apache-tomcat-7.0.75
tart tomcat
/opt/apache-tomcat-7.0.75
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Using CATALINA_TMPDIR: /opt/apache-tomcat-7.0.75/temp
 CATALINA_HOME:   /opt/apache-tomcat-7.0.75
tart tomcat
/opt/apache-tomcat-7.0.75
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Using JRE_HOME:        /usr
Using CLASSPATH:       /opt/apache-tomcat-7.0.75/bin/bootstrap.jar:/opt/apache-tomcat-7.0.75/bin/tomcat-juli.jar
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   Tomcat started.
       /usr
Using CLASSPATH:       /opt/apache-tomcat-7.0.75/bin/bootstrap.jar:/opt/apache-tomcat-7.0.75/bin/tomcat-juli.jar
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
outErr=
0

Process finished with exit code 0
原文地址:https://www.cnblogs.com/wushaopei/p/11979267.html