jiancai.wang jiancai.wang -4 years ago 178
Java Question

How do I get $JAVA_HOME by Jsch

#!/bin/sh
export JAVA_HOME=$(dirname $(dirname $(readlink -f $(which javac))))
echo JAVA_HOME=$(dirname $(dirname $(readlink -f $(which javac))))
echo JAVA_HOME=$JAVA_HOME
${JAVA_HOME}/bin/java -jar xxxxx


I want to execute this script on a remote machine in jsch:

public boolean actionShell(Session sshSession, String command) {
boolean flag = false;
Channel channel = null;
try {
channel = sshSession.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();

while (true) {
if (channel.isClosed()) {
if (in.available() > 0) continue;
flag = channel.getExitStatus() == 0 ? true : false;
log.info("exit-status: " + flag);
break;
}
Thread.sleep(1000);
}
} catch (Exception e) {
log.error("error", e.getMessage());
} finally {
if (channel != null || channel.isConnected())
channel.disconnect();
}
return flag;
}


The results show that this sh script can not get JAVA_HOME's value.

JAVA_HOME=
JAVA_HOME=
/bin/java -jar xxxxx


Because of we don't get conf of remote matchine, we can not point out the JAVA_HOME.

Answer Source

we can get a non-interactive and non-login shell and insert this code in script:

#!/bin/bash . /etc/profile . ~/.profile

non-interactive and non-login shell will not to to find and loading "BASH_ENV". there is a image show differences of file loading.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download