java远程连接linux,执行脚本启动Tomcat

Posted QW-lzm

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java远程连接linux,执行脚本启动Tomcat相关的知识,希望对你有一定的参考价值。

  /**
     * 1,依赖:
         <dependency>
             <groupId>ch.ethz.ganymed</groupId>
             <artifactId>ganymed-ssh2</artifactId>
             <version>build210</version>
         </dependency>
     * 
     * 
     * 2,tomcat启动报错:Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
     * 解决方法:
     *     Linux:
     *         在tomcat的bin目录下,编辑catalina.sh文件,加入
             export JAVA_HOME=/usr/soft/jdk1.8.0_162
             export JRE_HOME=/usr/soft/jdk1.8.0_162/jre
     *         这两行,重新启动就正常!
     * 
     *     Windows:
     *         在setclasspath.bat的开头声明环境变量
             set JAVA_HOME=E:Javajdk1.8.0_151
             set JRE_HOME=E:Javajre8
     * 
     * 
     * 3,restart.sh
     *     
         #!/bin/sh
        tomcat_dirname=`cd /usr/soft/tomcat ; pwd`
         
        pid=`ps -ef| grep ${tomcat_dirname}| grep -v "grep"| awk ‘{print $2}‘`
         
        if [ -n "${pid}" ];then
            echo "Will shutdown Tomcat: ${pid}"
            kill -9 ${pid}
            sleep 2
            sh ${tomcat_dirname}/bin/startup.sh
         
            new_pid=`ps -ef| grep ${tomcat_dirname}| grep -v "grep"| awk ‘{print $2}‘`
         
            if [ -n "${new_pid}" ];then
                echo "Tomcat has been started.The new pid is ${new_pid}!"
                sleep 2
                #tail -f ${tomcat_dirname}/logs/catalina.out
            else
                echo "Tomcat did not start!" 
            fi
        else
            echo "No Tomcat process! Start in 3 seconds"
            sleep 3    
            sh ${tomcat_dirname}/bin/startup.sh
            #tail -f ${tomcat_dirname}/logs/catalina.out
        fi
     * 
     * 
     * 4,赋予脚本权限
     *     chmod 777 restart.sh
     *  
     */

 

案例java代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class RemoteShellExecutor {
    
    private static String DEFAULTCHART = "UTF-8";

    private static Connection login(String ip, String username, String password) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = new Connection(ip);
            connection.connect();// 连接
            flag = connection.authenticateWithPassword(username, password);// 认证
            if (flag) {
                System.out.println("================登录成功==================");
                return connection;
            }
        } catch (IOException e) {
            System.out.println("=========登录失败=========" + e);
            connection.close();
        }
        return connection;
    }

    /**
     * 远程执行shll脚本或者命令
     * 
     * @param cmd
     *            即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    private static String execmd(Connection connection, String cmd) {
        String result = "";
        try{
            if (connection != null) {
                Session session = connection.openSession();// 打开一个会话
                session.execCommand(cmd);// 执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                System.out.println(result);
                // 如果为得到标准输出为空,说明脚本执行出错了
                /*if (StringUtils.isBlank(result)) {
                    System.out.println("得到标准输出为空,链接conn:" + connection + ",执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                } else {
                    System.out.println("执行命令成功,链接conn:" + connection + ",执行的命令:" + cmd);
                }*/
                connection.close();
                session.close();
            }
        } catch (IOException e) {
            System.out.println("执行命令失败,链接conn:" + connection + ",执行的命令:" + cmd + "  " + e);
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 解析脚本执行返回的结果集
     * 
     * @param in
     *            输入流对象
     * @param charset
     *            编码
     * @return 以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "
");
                System.out.println(line);
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            System.out.println("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
       
        String ip = "ip.xx.xx.xx";
        String username = "root";
        String password = "xxxx";
        
        String cmd = "sh /usr/soft/restart.sh";
        Connection connection = login(ip, username, password);
        String execmd = execmd(connection, cmd);
        
        System.out.println(execmd);
        long end = System.currentTimeMillis();
        System.out.println("ganymed-ssh2方式: "+(end - start)+"ms");
    }

}

 

以上是关于java远程连接linux,执行脚本启动Tomcat的主要内容,如果未能解决你的问题,请参考以下文章

Java 连接远程Linux 服务器执行 shell 脚本查看 CPU内存硬盘信息

Java 连接远程Linux 服务器执行 shell 脚本查看 CPU内存硬盘信息

使用secureCRT远程Linux,出现远程主机拒绝连接。

Tomca启动脚本遇到的坑

python 模拟 ssh 执行远程命令

ssh连接远程主机执行脚本的环境变量问题