如何在JSch中设置Java home来执行命令?

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

我正在使用 Jcraft JSch 通过 ssh 连接到远程机器并执行命令。由于它是非交互式 shell,因此找不到 Java 家。使用 jsch 时如何设置 Java home?看起来像

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

已弃用?

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();
}

我在执行命令时遇到错误

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

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。它可能不是什么。

您可以使用 PuTTY 进行同样的尝试 (Connection > Data > Environment variables)。您可能会收到 "Server refused to set environment variables" 消息。

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


无论如何,正确的解决方案是修复服务器配置以正确设置环境,即使对于非交互式会话也是如此。

或者作为一种肮脏的解决方法,您可以直接在命令中设置变量:

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

另见