代码之家  ›  专栏  ›  技术社区  ›  Stéphane GRILLON

如何通过java(jsch,如果可能)向Cisco/Alcatel交换机运行“显示接口状态”

  •  0
  • Stéphane GRILLON  · 技术社区  · 7 年前

    我需要跑步 show interfaces status 通过java连接到Cisco/Alcatel交换机(如果可能,请使用jsch)

    我使用SSH访问这个swith。在我尝试之后

    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    channel.setOutputStream(System.out);
    InputStream in = channel.getInputStream();
    channel.connect();
    

    我试着这样做(如果我在控制台中手动运行命令,可以)

    Channel channel = session.openChannel("shell");
    channel.setInputStream(null);
    channel.connect();
    

    我需要连接、发送命令并记录命令结果。如果我手动执行,结果就可以了。我在虚拟机中尝试我的代码,结果与物理交换机不同。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Duega    7 年前

    你可以试试这个:

    Channel channel=null;
    String result = null;
    
    try
    {
                channel = session.openChannel("exec");
                String Command = "show interfaces status";   // Command
                //System.out.println("Command : "+Command);
                ((ChannelExec)channel).setCommand(Command);
                InputStream in=channel.getInputStream();
                byte[] tmp=new byte[1024];
                channel.connect();
                if(channel.isConnected())
                {
                    //System.out.println("Channel connected");
                }
                while(true)
                {    // geeting the result in this loop
                    while(in.available()>0)
                                    {
                        int i=in.read(tmp, 0, 1024);
                        if(i<0)break;
                        result += new String(tmp, 0, i);    // result
                    }
                    if(channel.isClosed())
                    {
                        break;
                    }
                    else
                    {
                        try{ Thread.sleep(1000); }catch(Exception ee){}
                    }
                }
            }
    catch(JSchException e)
    {
                // your exception message
    }