Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete remote Non Empty folders with Java & SFTP

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?

like image 317
Hector Avatar asked Dec 04 '22 07:12

Hector


2 Answers

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

like image 55
Dinesh K Avatar answered Dec 29 '22 12:12

Dinesh K


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().

like image 21
nablex Avatar answered Dec 29 '22 10:12

nablex