【问题标题】:Providing input/subcommands to command executed over SSH with JSch Using JSF使用 JSF 为通过 SSH 执行的命令提供输入/子命令
【发布时间】:2017-08-19 23:44:33
【问题描述】:

我正在尝试使用 JSF 将路由器配置发送到 TFTP 服务器。当我使用 Main 类测试我的代码时它可以工作,但是当我尝试将此代码集成到按钮操作中时它不起作用。 这是我的会话 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 有问题。谁能帮帮我。

【问题讨论】:

    标签: java jsf ssh router jsch


    【解决方案1】:

    您没有向我们提供任何信息,我们可以使用这些信息来调试您的问题。 “它不起作用”不是问题描述。


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

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

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

    或者保留您的command output stream reading code from your original question(您不必将输出传递到任何地方):

    InputStream in = channelExec.getInputStream();
    
    // ...
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line;
    while ((line = reader.readLine()) != null)
    {
    }
    
    session.disconnect();
    

    【讨论】:

      猜你喜欢
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多