Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ori229
Last active November 13, 2022 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ori229/d340638e3b03bb36f4e893b3c1681a16 to your computer and use it in GitHub Desktop.
Save ori229/d340638e3b03bb36f4e893b3c1681a16 to your computer and use it in GitHub Desktop.
Java access to SFTP with a private key
import java.util.Vector;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
public class TestSftpWithPrivateKey {
static final String PRIVATE_KEY_FILE = "C:\\temp\\id_rsa.txt";
static final String SFTP_USER = "alma_01abcde_inst@customers.na";
static final String SFTP_HOST = "custdata-dc04.hosted.exlibrisgroup.com";
static final int SFTP_PORT = 10022;
static final String SFTP_DIR = "sandbox/subdir";
static final int DEL_FILES_OLDER_THAN_IN_DAYS = 20;
public static void main(String[] args) {
JSch jSch = new JSch();
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
jSch.addIdentity(PRIVATE_KEY_FILE);
System.out.println("Private Key Added.");
session = jSch.getSession(SFTP_USER, SFTP_HOST, SFTP_PORT);
System.out.println("Session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
System.out.println("Shell channel connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTP_DIR);
System.out.println("Changed the directory to " + SFTP_DIR);
int unixTimeNow = (int) (System.currentTimeMillis() / 1000);
Vector<LsEntry> filesInDir = channelSftp.ls(".");
for (LsEntry sftpFile : filesInDir) {
String fileName = sftpFile.getFilename();
if (fileName.startsWith("."))
continue;
SftpATTRS attrs = sftpFile.getAttrs();
int mTime = attrs.getMTime();
int modifiedSecAgo = unixTimeNow - mTime;
int modifiedDaysAgo = (modifiedSecAgo) / 60 / 60 / 24;
System.out.println(sftpFile + " is " + modifiedDaysAgo + " days old");
if (modifiedDaysAgo > DEL_FILES_OLDER_THAN_IN_DAYS) {
System.out.println("Deleting " + fileName);
channelSftp.rm(fileName);
}
}
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.disconnect();
channelSftp.exit();
}
if (channel != null)
channel.disconnect();
if (session != null)
session.disconnect();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment