Question

I have a requirement to delete multiple non empty folders on multiple UNIX servers. I am looking to use something like Apache FileUtils, which allows non empty LOCAL folders to be deleted. Its just that my folders in this case are REMOTE. Do i have to first list all the files contained in each remote folder, deleting each file found in turn? Or... Is there a java SFTP/SSH client that exposes the functionality of FileUtils.deleteDirectory() for remote folder removal?

Was it helpful?

Solution 2

I'm not entirely sure if it has a native recursive delete() (this is trivial to implement yourself though) but jsch (http://www.jcraft.com/jsch/) is an awesome implementation that allows for sftp access. We use it all the time.

Example code for connection:

JSch jsch = new JSch();
Properties properties = new Properties();
properties.setProperty("StrictHostKeyChecking", "no");

if (privKeyFile != null)
    jsch.addIdentity(privKeyFile, password);

Session session = jsch.getSession(username, host, port);
session.setTimeout(timeout);
session.setConfig(properties);

if (proxy != null)
    session.setProxy(proxy);

if (privKeyFile == null && password != null)
    session.setPassword(password);

session.connect();

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

The channel has rm() and rmdir().

OTHER TIPS

You can delete folder using JSCH java API. Below is the sample code for deleting non empty folder with java and SFTP.

@SuppressWarnings("unchecked")
private static void recursiveFolderDelete(ChannelSftp channelSftp, String path) throws SftpException {

    // List source directory structure.
    Collection<ChannelSftp.LsEntry> fileAndFolderList = channelSftp.ls(path);

    // Iterate objects in the list to get file/folder names.
    for (ChannelSftp.LsEntry item : fileAndFolderList) {
        if (!item.getAttrs().isDir()) {
            channelSftp.rm(path + "/" + item.getFilename()); // Remove file.
        } else if (!(".".equals(item.getFilename()) || "..".equals(item.getFilename()))) { // If it is a subdir.
            try {
                // removing sub directory.
                channelSftp.rmdir(path + "/" + item.getFilename());
            } catch (Exception e) { // If subdir is not empty and error occurs.
                // Do lsFolderRemove on this subdir to enter it and clear its contents.
                recursiveFolderDelete(channelSftp, path + "/" + item.getFilename());
            }
        }
    }
    channelSftp.rmdir(path); // delete the parent directory after empty
}

For more details. Please refer the link here

Unfortunately, the sftp protocol does not allow to delete the non-empty directory, and jsch has not implemented the recursive deletion of such directories. If you don't want to implement recursive deletion by yourself, how about executing "rm -rf" on jsch's exec channel?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top