Jsch : Command Output unavailable

烈酒焚心 提交于 2019-12-02 06:34:29

问题


I am trying to use jsch to connect to a remote switch and run some command and extract the output.

I am able to connect to the switch using , however the command output is not available in the inputstream. Maybe i am not doing it the right way. Here's the code

    session = jsch.getSession("user", "10.0.0.0", 22);
    session.setPassword("somepwd");
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    System.out.println("connected to remote host");
    Channel channel = session.openChannel("shell");

     OutputStream ops = channel.getOutputStream();
     PrintStream ps = new PrintStream(ops);
        channel.connect();
            ps.println("show version"); 
            ps.flush();
            ps.close();
            InputStream in=channel.getInputStream();
            byte[] bt=new byte[1024];


            while(in.available()>0)
            {
                int i=in.read(bt, 0, 1024);
                if(i<0)
                 break;
                    String str=new String(bt, 0, i);
                //displays the output of the command executed.
                    System.out.print(str);
            }

    channel.disconnect();
    session.disconnect();

When i debug the inputStream.isAvailable() always returns zero suggesting that there is no output from the command.

TIA!


回答1:


Please try the code below - tested and working

    Channel channel = session.openChannel("shell");
    OutputStream ops = channel.getOutputStream();
    PrintStream ps = new PrintStream(ops);
    channel.connect();
    ps.println("pwd");
    ps.println("exit");
    ps.flush();
    ps.close();

    InputStream in = channel.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    System.out.println("Opening...");

    String jarOutput;
    while ((jarOutput = reader.readLine()) != null)
        System.out.println(jarOutput);
    reader.close();
    channel.disconnect();

Output -

Opening...
user@host:~> pwd
/home/user
user@host:~>
user@host:~> exit
logout



来源:https://stackoverflow.com/questions/25761400/jsch-command-output-unavailable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!