使用net.schmizz.sshj.sftp.SFTPClient api识别SSH机器上的文件或目录。

时间:2013-04-01 16:37:58

标签: ssh

我想确定给定路径是否是使用net.schmizz.sshj.sftp.SFTPClient api的文件或目录的有效路径,并且基于我需要做出决定,如果它是有效的文件路径,那么我需要访问其父目录。我的代码如下所示>         SSHClient ssh = new SSHClient();         String rsaKey =“e3:27:12:a9:62:9a:46:cc:98:ee:0d:b7:38:72:a0:63”;         String host =“10.235.1.154”;         String uName =“root”;         String pwd =“pspl @ 123”;         String url =“/ root / ram2.log /”;         String testUrl = host + url;         ssh.addHostKeyVerifier(rsaKey);         列出fileItems = new ArrayList();

    1.try {
    2.  ssh.connect(host);
    3.  ssh.authPassword(uName,pwd);
    4.  SFTPClient sftp = ssh.newSFTPClient();
    5.  
    6.  if(testUrl.startsWith(host)){
    7.      String[] splitedStrings = testUrl.split(host);
    8.      String str = splitedStrings[1];
    9.      url = str;
    10. }else{
    11.     url = url;
    12. }
    13. 
    14.
    15. List<RemoteResourceInfo> fileInfoList = sftp.ls(url, new RemoteResourceFilter() {
    16.     public boolean accept(RemoteResourceInfo rrInfo) {
    17.         return rrInfo.getName().charAt(0) != '.';
    18.     }
    19. });
    20. 
    21. 
    22. for (RemoteResourceInfo fileInfo : fileInfoList) {
    23.     //files.add(str + "/" + fileInfo.getName());
    24.     String fileName = fileInfo.getName();
    25.     if (fileInfo.isDirectory()) {
                FileItem childFileItem = new FileItem();
                childFileItem.setPath(host + url + fileName);
                fileItems.add(childFileItem);
            } else {
                int dotIndex = fileName.lastIndexOf('.');
                String ext = dotIndex > 0 ? fileName
                        .substring(dotIndex + 1) : "";
                FileItem childFileItem = new FileItem();
                childFileItem.setPath(host + url + fileName);
                childFileItem.setDirectory(false);
                fileItems.add(childFileItem);
            }
        }




    } catch (IOException e) {
        System.out.println("Couldn't resolve host : {} "+ host);
    }
    return fileItems;

问题:行号。如果我将路径设置为“/root/ram2.log/”,即使文件ram2.log在服务器上执行exis,也会抛出错误,说没有这样的文件。

任何有关这个问题的帮助都会有所帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用lstat获取有关文件系统对象的信息。

FileAttributes attributes = sftp.lstat(url);
if (attributes.getType() == FileMode.Type.DIRECTORY) {
    ...
}

但我认为你的实际问题是目录“/root/ram2.log/”有些奇怪。也许没有许可,也许它不可见,也许它包含一个名称编码不正确的文件。