javasshsftpapache-commons

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?


Solution

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