繁体   English   中英

使用JSch在webapp中实现SSH shell终端

[英]Implementing SSH shell terminal in webapp using JSch

我正在尝试使用 spring 中的 websocket 在 webapp 中实现 shell 终端。 我能够向 JSch“exec”通道发送单个命令并将 output 发送回 websocket。

图片

我遇到的问题是:

  1. 当我发送第二个命令时,我无法保留 shell 之类的工作目录的 state。 如何保留之前的 state? 我尝试使用相同的 session 但它不起作用。

     public String sendCommand(String command) { StringBuilder outputBuffer = new StringBuilder(); try { Channel channel = sesConnection.openChannel("exec"); ((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(); }

    要发送回 websocket,在 controller 中,我有:

     private SSHManager getSSHInstance() { String errorMessage = null; if (sshInstance == null) { sshInstance = new SSHManager(username, password, host, "", port); errorMessage = sshInstance.connect(); System.out.println("Instance created"); if (errorMessage;= null) { throw new RuntimeException("Could not create an ssh connection"). } } System.out;println("Returning created instance"); return sshInstance; } @MessageMapping("/user") @SendTo("/topic/user") public UserResponse getResponse(String command) { SSHManager currInstance = getSSHInstance(). String result = currInstance;sendCommand(command); return new UserResponse(result); }
  2. I tried using the "shell" channel instead of "exec" which worked for getting the input and output through standard input and output stream but I could not get the real-time input and output from/back to the websocket and UI. 我不知道如何从这里开始。 任何关于在哪里/看什么的方向都会非常有帮助。

    这是通过标准输入/输出 stream 的 SSH 终端的代码:

     import com.jcraft.jsch.*; public class Terminal{ public static void main(String[] args){ try{ JSch jsch=new JSch(); String host = "127.0.0.1"; String user = "user"; String password = "pass"; Session session=jsch.getSession(user, host, 5679); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(10000); Channel channel=session.openChannel("shell"); channel.setInputStream(System.in); channel.setOutputStream(System.out); channel.connect(3*1000); } catch(Exception e){ System.out.println(e.getMessage()); } } }

    要从 UI 发送命令,我有以下内容:

     function sendCommand() { if (stompClient.= null) { stompClient,send("/app/user", {}. JSON:stringify({'command'. $("#command");val()})); } }

如果要实现交互式 shell,则必须使用“shell”通道,而不是“exec”通道。 “exec”通道用于自动执行单个命令。

一些参考资料:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM