Friday, July 29, 2022

[SOLVED] How to set Java home in JSch to execute a command?

Issue

I'm using Jcraft JSch to ssh into a remote machine and execute a command. As it's a non-interactive shell it's not finding Java home. How do I set Java home while using jsch? looking like

((ChannelExec) channel).setEnv("LANG", "UTF-8");
((ChannelExec) channel).setEnv("JAVA_HOME", "/blah/java/J8.0_64/");

is deprecated?

public String sendCommand(String command) {
  StringBuilder outputBuffer = new StringBuilder();

  try {
     Channel channel = sesConnection.openChannel("exec");
     ((ChannelExec) channel).setEnv("LANG", "UTF-8");
     ((ChannelExec) channel).setEnv("JAVA_HOME", "/blah/java/J8.0_64/");
     ((ChannelExec) channel).setCommand(command);
     InputStream commandOutput = channel.getInputStream();
     channel.connect();
     int readByte = commandOutput.read();

     while (readByte != 0xffffffff) {
        outputBuffer.append((char) readByte);
        readByte = commandOutput.read();
     }

     channel.disconnect();
  } catch (IOException ioX) {
     logWarning(ioX.getMessage());
     return null;
  } catch (JSchException jschX) {
     logWarning(jschX.getMessage());
     return null;
  }

  return outputBuffer.toString();
}

Error I'm getting while executing a command

JAVA_HOME not set and cannot find javac to deduce location, please set JAVA_HOME.


Solution

ChannelExec.setEnv on JSch side probably works. But assuming you are connecting to an OpenSSH server, the server must be explicitly configured to allow you to set the LANG and JAVA_HOME environment variables using the AcceptEnv directive. What it probably is not.

You can try the same using PuTTY (Connection > Data > Environment variables). You will probably get "Server refused to set environment variables" message back.

See also How can I set environment variables when I ssh login to my Unix box by passing custom arguments?


Anyway, the correct solution is to fix your server configuration to set the environment correctly even for non-interactive sessions.

Or as a dirty workaround you can set the variables directly in your command:

JAVA_HOME=/blah/java/J8.0_64/; java ...

See also Certain Unix commands fail with "... not found", when executed through Java using JSch.



Answered By - Martin Prikryl
Answer Checked By - David Marino (WPSolving Volunteer)