我正在使用 Jcraft JSch ssh 到远程计算机并执行命令。由于它是一个非交互式 shell,因此它找不到 Java 主目录。使用 jsch 时如何设置 Java 主目录?看起来像
((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
在 JSch 方面可能有效。但假设您要连接到 OpenSSH 服务器,则必须显式配置服务器以允许您使用 AcceptEnv
directive 设置 LANG
和 JAVA_HOME
环境变量。 。它可能不是。
您可以使用 PuTTY ( Connection > Data > Environment variables ) 尝试相同的操作。您可能会收到“服务器拒绝设置环境变量”消息。
另请参阅How can I set environment variables when I ssh login to my Unix box by passing custom arguments?
<小时/>无论如何,正确的解决方案是修复服务器配置,以正确设置环境,即使对于非交互式 session 也是如此。
或者作为一种肮脏的解决方法,您可以直接在命令中设置变量:
JAVA_HOME=/blah/java/J8.0_64/; java ...
另请参阅Certain Unix commands fail with "... not found", when executed through Java using JSch .
关于java - 如何在JSch中设置Java home来执行命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57963430/