SSH Output is always empty

I've been trying to figure this out for hours and I can't figure it out. I am trying to use JSch to SSH to a Linux computer from an Android phone. The commands always work fine, but the channel output is usually empty. Sometimes it displays output, but most of the time it doesn't. Here is the code I found online.

       String userName = "user";
       String password = "test123";
       String connectionIP = "192.168.1.13";

       JSch jsch = new JSch();
       Session session;
       session = jsch.getSession(userName, connectionIP, 22);
       session.setPassword(password);

       // Avoid asking for key confirmation
       Properties prop = new Properties();
       prop.put("StrictHostKeyChecking", "no");
       session.setConfig(prop);
       session.connect();

       // SSH Channel

       ChannelExec channelssh = (ChannelExec) session.openChannel("exec");      
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       channelssh.setOutputStream(baos);

       // Execute command
       channelssh.setCommand("ls");
       channelssh.connect();        
       channelssh.disconnect();

       RESULT = baos.toString();

      

The RESULT is usually empty. If I change the command to mkdir or something similar, the files appear on the Linux machine, which leads me to believe that part of the command is working correctly. The problem seems to lie with the ByteArrayOutputStream. I also checked the connection, username and password on another computer via terminal, so I know the credentials are correct. I guessed this problem to death, any input will help me greatly!

+3


source to share


2 answers


Found the answer, I was reading the wrong thread. This is the correct code for others with this problem.



       InputStream inputStream = channelssh.getInputStream(); 

       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

       StringBuilder stringBuilder = new StringBuilder();

       String line;

       while ((line = bufferedReader.readLine()) != null) 
       {

           stringBuilder.append(line);
           stringBuilder.append('\n');

       }

       return stringBuilder.toString();   

      

+3


source


The exec channel will be started on a different thread, so you need to wait for it to complete before calling Channel # disconnect ().



0


source







All Articles