提供 input/subcommands 以通过 SSH 使用 JSch 使用 JSF 执行的命令

Providing input/subcommands to command executed over SSH with JSch Using JSF

我正在尝试使用 JSF 将路由器配置发送到 TFTP 服务器。当我使用 Main class 测试我的代码时,它可以工作,但是当我尝试将此代码集成到按钮操作中时,它不起作用。 这是我的会话 bean 代码

public Void SendConfigViaTftp(Router r) {
        int port=22;
        String name = r.getRouterName();
        String ip=r.getRouterIP();
        String password =r.getRouterPassword();
        try
            {
            JSch jsch = new JSch();
            Session session = jsch.getSession(name, ip, port);
                session.setPassword(password);
                session.setConfig("StrictHostKeyChecking", "no");
            System.out.println("Establishing Connection...");
            session.connect();
                System.out.println("Connection established.");


                ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

                InputStream in = channelExec.getInputStream();
             channelExec.setCommand("enable");

         channelExec.setCommand("copy run tftp:");
         OutputStream out = channelExec.getOutputStream();

         channelExec.connect();

         System.out.println("Copy.");
         out.write(("192.168.18.1 \n").getBytes());
         System.out.println("IP.");
         out.write(name.getBytes());
         System.out.println("name.");
         out.flush();
         out.close();


                session.disconnect();
                return true;


                }
        catch(Exception e){System.err.print(e);

       }


}

这是输出:

11:53:25,279 INFO [stdout](默认任务 11)正在建立连接...

11:53:25,516 INFO [stdout](默认任务 11)已建立连接。

11:53:25,578 INFO [stdout](默认任务 11)复制。

11:53:25,578 INFO [stdout](默认任务 11)IP。

11:53:25,578 INFO [stdout](默认任务 11)名称。

这是我的按钮代码

<p:commandButton value="Sauvegarder(TFTP)" action="#{ListBean.sauvegardeTFTP(rtr)}" update=":routeurs" ><f:ajax disabled="true"/></p:commandButton>

我确定问题是我的 jsf 应用程序的 OutputStream 有问题。谁能帮帮我。

您没有向我们提供我们可以用来调试您的问题的任何信息。 "it doesn't work"不是问题描述。


无论如何,一个明显的问题是,您删除了读取命令输出的代码,并且没有用其他方式替换它以等待命令完成。因此很有可能连接在命令完成之前就终止了,从而终止了命令。

等待频道关闭,然后再关闭会话:

while (!channelExec.isClosed()) Thread.sleep(100);

或者保留你的(你不必在任何地方传递输出):

InputStream in = channelExec.getInputStream();

// ...

BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null)
{
}

session.disconnect();