背景:这两天搞了一下java的跨系统远程调用,遇到了几个问题,其中最让我头疼的就是下面那个,然而最后也解决了,故写下来总结一下

Neither the JAVA_HOME nor the JRE_HOME environment variable is defined

我是用的第三方连接远程系统,即ganymed-ssh2

<dependency>
	<groupId>ch.ethz.ganymed</groupId>
	<artifactId>ganymed-ssh2</artifactId>
	<version>build210</version>
</dependency>

在我编写完代码之后,运行出现了好几个问题,比如利用java运行远程服务器的脚本出现not permission>学过编程的人肯定都知道这是没有权限,给它个权限就好了,即 chmod 777 /data/xxx(即路径).当然,这个不是重点,略过… 说一下调用/tomcat/bin/startup.sh 出现Neither the JAVA_HOME nor the JRE_HOME environment variable is defined,为什么呢?大概是因为用java远程登录不能获取到环境变量吧! file

然后贴上java连接的代码


import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.extern.slf4j.Slf4j; 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;


@Slf4j
public class ServerUtils {

    private Connection conn;
    private String ip;
    private String username;
    private String password;
    private static final int TIME_OUT = 3;

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerUtils.class);
    /***
     * 分割  获取PID
     */
    private static final String SPLIT = "     ";



    /**
     * 构造函数
     */
    public ServerUtils(ServerEnum serverEnum) {
        this.ip = serverEnum.getIp();
        this.username = serverEnum.getName();
        this.password = serverEnum.getPassword();
    }


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

    /**
     * 启动
     */
    public boolean start(ServerEnum serverEnum, ProjectEnum projectEnum) {
        try {
		    //脚本地址 
            // /data/bash/tomcat.sh
            String path = CommandUtils.getStartBash(serverEnum, projectEnum);
            exec(path);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    } 

    /**
     * 执行脚本
     *
     * @param shell
     * @return
     * @throws Exception
     */
    public String exec(String shell) throws Exception {
        try {
            shell += " ";
            if (login()) {
                LOGGER.info(">>>>登录成功!!!登录服务器IP为>>>>>>{}",this.ip);
                Session session = conn.openSession();
                LOGGER.info(">>>>>>>>开始执行shell 命令>>>>>>{}", shell);
                session.execCommand(shell);
                String returnValue = processStdout(session.getStdout());
                LOGGER.info("执行结束,返回值是>>>>>>>>>>{}",returnValue);
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
                session.getExitStatus();
                return CommandUtils.getFirstLine(returnValue);
            } else {
                LOGGER.error("登录远程机器失败,serverIP is {}" + ip);
                throw new RuntimeException("登录远程机器失败");
            }
        } finally {
            if (conn != null) {
                conn.close();
            }
        }

    }

    /**
     * 对服务器打印的值进行解析
     * @return
     * @throws Exception
     */
    private String processStdout(InputStream in) {
        InputStream stdout = new StreamGobbler(in);
        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, Charset.defaultCharset()));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
                break;
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    public static void main(String[] args) throws Exception { 
        new ServerUtils(ServerEnum.test2).start(ServerEnum.test2, ProjectEnum.ent); 
    }
}

file

解决办法:

在服务器上编写一个脚本,手动设定它的jdk环境变量,创建一个脚本tomcat.sh,编写如下:

#! /bin/bash
TOMCAT_NAME=tomcat-crm
PROJECT_PATH=/pm/server/$TOMCAT_NAME
DATE=`date +%Y-%m-%d--%H-%M-%S`
###设置java变量
export JAVA_HOME=/data/server/jdk1.8.0_181
./startup.sh 

在调用java -jar 进行启动springboot项目的时候也发现了此类问题,尽管加上export JAVA_HOME=xxxx也没什么用, 在这里加入下面的命令完美解决springboot远程启动的问题, **source /etc/profile;nohup java -jar /mnt/test.jar & **