2
votes

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.

2
((ChannelExec) channel).setCommand(command); Could you edit your question to include an example of the actual command that you're trying to run here? - Kenster
@Kenster ((ChannelExec) channel).setCommand(command) is part of the test method I'm using. Actual test has the command in it and its trying to run a build. The problem is not with the command but looks like it needs the java home to run this command. - arthi

2 Answers

1
votes

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.

0
votes

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+"'");