当前位置: 首页 > 工具软件 > bash-commons > 使用案例 >

java piee,从Java通过SSH执行Bash命令时出现问题

景轶
2023-12-01

我无法通过SSH从

Java在远程GNU /

Linux系统上执行命令.在本地Bash中执行时,以下命令可以正常工作(当然用户和主机不同但行为不变).

$ssh user@host.example.com 'hostname'

host

$ssh user@host.example.com 'hostname -f'

host.example.com

$ssh user@host.example.com "hostname -f"

host.example.com

在没有参数的情况下,执行我认为与Java相同的任何事情都会失败.

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import org.apache.commons.exec.CommandLine;

import org.apache.commons.exec.DefaultExecutor;

import org.apache.commons.exec.Executor;

import org.apache.commons.exec.PumpStreamHandler;

public class SOPlayground {

public static void main(String[] args) throws Exception {

for (String argument : new String[]{"hostname", "'hostname'", "\"hostname\"",

"'hostname -f'", "\"hostname -f\""}) {

CommandLine commandLine = new CommandLine("ssh");

commandLine.addArgument("user@host.example.com");

commandLine.addArgument(argument);

System.out.println(commandLine);

final Executor executor = new DefaultExecutor();

try (ByteArrayOutputStream os = new ByteArrayOutputStream();

ByteArrayOutputStream err = new ByteArrayOutputStream()) {

executor.setStreamHandler(new PumpStreamHandler(os, err));

int exitcode = executor.execute(commandLine);

System.out.println("exitcode=" + exitcode);

System.out.println(new String(os.toByteArray(), "UTF-8"));

System.err.println(new String(err.toByteArray(), "UTF-8"));

} catch (IOException ex) {

System.err.println(ex.getMessage());

}

}

}

}

输出是:

ssh user@host.example.com hostname

exitcode=0

host

ssh user@host.example.com 'hostname'

exitcode=0

host

ssh user@host.example.com "hostname"

exitcode=0

host

ssh user@host.example.com 'hostname -f'

Process exited with an error: 127 (Exit value: 127)

ssh user@host.example.com "hostname -f"

Process exited with an error: 127 (Exit value: 127)

如您所见,通过SSH从Java执行主机名-f失败,退出代码为127.我想知道bash(本地或远程)无法找到什么命令.

我试过用这个变种

addArgument(String argument, boolean handleQuoting)

但结果没有差别.

我如何从通过SSH工作的Java构建CommandLine?

 类似资料: