有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为使用JSF通过SSH和JSch执行的命令提供输入/子命令

我正在尝试使用JSF将路由器的配置发送到TFTP服务器。当我用Main类测试代码时,它是有效的,但当我试图将代码集成到button action中时,它就不起作用了。 这是我的会话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:25279信息[stdout](默认任务-11)正在建立连接

11:53:25516信息[stdout](默认任务11)已建立连接

11:53:25578信息[stdout](默认任务-11)复制

11:53:25578信息[stdout](默认任务11)IP

11:53:25578信息[stdout](默认任务-11)名称

这是我按钮的代码

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

我确信问题在于我的jsf应用程序的OutputStream有问题。谁能帮帮我吗


共 (1) 个答案

  1. # 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();