0

I am supposed to connect to a Unix server, then go to the specific folder(which has got access restrictions) and fetch the file details from there. For the same , the code that I have written is

try{

            Session session = new JSch().getSession("username", "host"); 
            session.setPassword("password");
            java.util.Properties config = new java.util.Properties(); 
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            Channel channel=session.openChannel("exec");
            ((ChannelExec)channel).setCommand("cd a/b/node01/c.ear && ls -la");
            channel.connect();
            channel.run();
            InputStream in = channel.getInputStream();

            System.out.println(channel.isConnected());

            byte[] tmp = new byte[1024];
            while (true)
            {
              while (in.available() > 0)
              {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                  break;
                System.out.print(new String(tmp, 0, i));
              }
              if (channel.isClosed())
              {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
              }

            }



            channel.disconnect();
            session.disconnect();
        }
        catch(Exception exception){
            System.out.println("Got exception "+exception);
        }

I am not getting the list of files that are present in the location supplied. The output that I am getting is

true

exit-status: 1

How do I get the desired output?

Random Coder
  • 329
  • 2
  • 5
  • 11

2 Answers2

1

Do not use shell commands to retrieve file information. Use SFTP!

Channel channel = session.openChannel("sftp");
channel.connect();

ChannelSftp c = (ChannelSftp)channel;
java.util.Vector vv = c.ls("/a/b/node01/c.ear");

for (int i = 0; i < vv.size(); i++)
{
    System.out.println(vv.elementAt(i).toString());
}

See http://www.jcraft.com/jsch/examples/Sftp.java.html


Regarding your code for "exec" channel:

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
0

A possible problem here is the usage of in.available(). It returns the number of bytes that can be read without blocking.

The correct way to read a stream until eof is:

byte[] buf = new byte[1024];
int len;
while ((len=in.read(buf)) >= 0) {
   // do something with buf[0 .. len]
}
Henry
  • 42,982
  • 7
  • 68
  • 84