使用 JSch 时,您必须使用InputStream
SSH 客户端与服务器之间的通信以及服务器与OutputStream
客户端之间的通信。这可能不是很直观。
以下示例使用管道流来提供更灵活的 API。
创建一个 JSch 会话...
Session session = new JSch().getSession("user", "localhost", port);
session.setPassword("secret");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
如果你想向一个 shell 发送多个命令,你应该使用ChannelShell
如下:
ChannelShell channel = (ChannelShell) session.openChannel("shell");
PipedInputStream pis = new PipedInputStream();
channel.setInputStream(pis);
PipedOutputStream pos = new PipedOutputStream();
channel.setOutputStream(pos);
channel.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new PipedOutputStream(pis)));
writer.write("echo Hello World\n");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(new PipedInputStream(pos)));
String line = reader.readLine(); // blocking IO
assertEquals("Hello World", line);
在 an 的帮助下,ByteArrayOutputStream
您还可以以非阻塞方式进行通信:
ChannelShell channel = (ChannelShell) session.openChannel("shell");
channel.setInputStream(new ByteArrayInputStream("echo Hello World\n".getBytes()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channel.setOutputStream(baos);
channel.connect();
sleep(1000); // needed because of non-blocking IO
String line = baos.toString();
assertEquals("Hello World\n", line);
如果您只想发送一个命令ChannelExec
就足够了。如您所见,输出流的工作方式与以前相同:
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand("echo Hello World");
PipedOutputStream pos = new PipedOutputStream();
channel.setOutputStream(pos);
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(new PipedInputStream(pos)));
String line = reader.readLine(); // blocking IO
assertEquals("Hello World", line);