Unix命令变为cd和ls -la,可通过Java代码运行 [英] Unix commands become, cd and ls -la to be run via java code

查看:81
本文介绍了Unix命令变为cd和ls -la,可通过Java代码运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该连接到Unix服务器,然后转到特定的文件夹(具有访问限制),然后从那里获取文件详细信息.同样,我编写的代码是

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

退出状态:1

如何获得所需的输出?

推荐答案

请勿使用Shell命令检索文件信息.使用SFTP!

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());
}

请参见 http://www.jcraft.com/jsch/examples/Sftp.java.html

关于"exec"频道的代码:

Regarding your code for "exec" channel:

  • First, the code has a recurring flaw described in:
    Randomly getting empty output while executing shell command via JSch.
  • Though to actually debug your problem, you have to read both stdout and stderr to collect any errors (which you are obviously getting).
    For that see Log stdout and stderr from ssh command in the same order it was created.

这篇关于Unix命令变为cd和ls -la,可通过Java代码运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆