【问题标题】:Unix commands become, cd and ls -la to be run via java codeUnix 命令变为,cd 和 ls -la 将通过 java 代码运行
【发布时间】:2020-03-10 03:49:42
【问题描述】:

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

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

我没有获得提供的位置中存在的文件列表。 我得到的输出是

是的

退出状态:1

如何获得所需的输出?

【问题讨论】:

  • “cd a/b/node01/”真的指向一个有效的目录吗?你试过绝对路径吗?
  • 我建议阅读频道错误流
  • 是的,这是一个有效的目录。当我通过 Putty 访问时,发出 ls -la 命令后,我可以看到目录中的文件。
  • 您应该为此使用 SFTP,而不是普通的 SSH。
  • 即使使用 SFTP,我也会收到权限被拒绝错误,因为要发出 ls -la 命令的目录是受限目录。

标签: java unix jsch


【解决方案1】:

不要使用 shell 命令来检索文件信息。使用 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”频道的代码:

【讨论】:

    【解决方案2】:

    这里可能存在的问题是in.available() 的使用。它返回不阻塞可以读取的字节数。

    在 eof 之前读取流的正确方法是:

    byte[] buf = new byte[1024];
    int len;
    while ((len=in.read(buf)) >= 0) {
       // do something with buf[0 .. len]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      • 2015-06-10
      • 2012-06-24
      • 2011-10-16
      • 2018-05-10
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多