How to set Java home in JSch to execute a command?


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();
     int readByte =;

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

  } catch (IOException ioX) {
     return null;
  } catch (JSchException jschX) {
     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.

asked on Stack Overflow Sep 16, 2019 by arthi • edited Sep 17, 2019 by Martin Prikryl

1 Answer


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 on Stack Overflow Sep 17, 2019 by Martin Prikryl • edited Sep 17, 2019 by Martin Prikryl

User contributions licensed under CC BY-SA 3.0