2

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.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
arthi
  • 193
  • 4
  • 17

2 Answers2

1

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.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • 1
    Thanks Martin. Will try to fix server configuration to set the environment correctly for non-interactive sessions. – arthi Sep 17 '19 at 13:47
0

This got me when I was trying to run maven using jsch exec.

Easy work-around is to use bash to run your command.

String command = "bash --login -c 'mvn --version'";
((ChannelExec) channel).setCommand(command);

or

((ChannelExec) channel).setCommand("bash --login -c '"+command+"'");
bhlowe
  • 418
  • 4
  • 8