SFTP connection with key file example

Click here to download eclipse supported ZIP file



This is input.properties properties file and these properties are used in the application.




key_authentication.source.fileLocation=C:/temp/cv/
key_authentication.backup.fileLocation=C:/temp/cv/backup/
key_authentication.sftp.address=<IP>
key_authentication.sftp.user=UserName
key_authentication.sftp.destination.fileLocation=./test/
key.file.location=C:/temp/cv/
#Mention the value of MODE_OF_CONNECTIONS as key for key authentication, basic for username/password authentication and all for both.
MODE_OF_CONNECTIONS=key
message=There is a problem in the server.
host=smtp.sendgrid.net
port=25
ccAddress=XXX@gmail.com
toAddress=xxxx.xxx@gmail.com
fromAddress=xxx@xxxx.com
username=username
password=password


This is AppInit.java file having the source code to execute business logic.



 

    
package com.cv.sftp.key.auth;

import java.net.URL;
import java.util.Properties;

/**
 @author Chandra Vardhan
 *
 */
public class AppInit {

  static String keyAuthAddress = null;
  static String keyAuthUserId = null;
  static String keyAuthDestinationDirectory = null;
  static String keyAuthSourceDirectory = null;
  static String keyAuthBackupDirectory = null;

  static String authMode = null;

  static String message = null;
  static String host = null;
  static String port = null;
  static String ccAddress = null;
  static String fromAddress = null;
  static String toAddress = null;
  static String userName = null;
  static String password = null;
  static Properties readPropertiesFile = new Properties();
  static URL url = null;

  static {
    readPropertiesFile = readPropertiesFile();
    setValues(readPropertiesFile);
    url = readAuthKeyFile();
  }

  private static void setValues(Properties readPropertiesFile2) {
    if (readPropertiesFile2 != null) {
    
      keyAuthAddress = readPropertiesFile2.getProperty("key_authentication.sftp.address");
      keyAuthUserId = readPropertiesFile2.getProperty("key_authentication.sftp.user");
      keyAuthDestinationDirectory = readPropertiesFile2
          .getProperty("key_authentication.sftp.destination.fileLocation");
      keyAuthSourceDirectory = readPropertiesFile2.getProperty("key_authentication.source.fileLocation");
      keyAuthBackupDirectory = readPropertiesFile2.getProperty("key_authentication.backup.fileLocation");
      authMode = readPropertiesFile2.getProperty("MODE_OF_CONNECTIONS");

      message = readPropertiesFile2.getProperty("message");
      host = readPropertiesFile2.getProperty("host");
      port = readPropertiesFile2.getProperty("port");
      ccAddress = readPropertiesFile2.getProperty("ccAddress");
      fromAddress = readPropertiesFile2.getProperty("fromAddress");
      toAddress = readPropertiesFile2.getProperty("toAddress");
      userName = readPropertiesFile2.getProperty("username");
      password = readPropertiesFile2.getProperty("password");
    }
  }

  private static Properties readPropertiesFile() {
    Properties props = new Properties();
    try {
      props.load(AppInit.class.getClassLoader().getResourceAsStream("input.properties"));
    catch (Exception e) {
      System.err.println("Problem while reading input properties file!!!");
    }
    return props;
  }

  private static URL readAuthKeyFile() {
    URL url = null;
    try {
      url = AppInit.class.getClassLoader().getResource("privateKey.pub");
    catch (Exception e) {
      System.err.println("Problem while reading auth-key file!!!");
    }
    return url;
  }

}


This is EmailUtility.java file having the source code to execute business logic.



 

    
package com.cv.sftp.key.auth;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 @author Chandra Vardhan
 *
 */
public class EmailUtility {

  public static void sendEmail(final String subject, final String content) {
    try {

      // Get the session object
      Properties properties = new Properties();
      final String userName = AppInit.userName;
      final String password = AppInit.password;
      final String port = AppInit.port;
      final String host = AppInit.host;
      properties.setProperty("mail.smtp.host", host);
      properties.setProperty("port", port);
      properties.put("mail.smtp.auth""true");
      properties.put("mail.smtp.starttls.enable""true");
      properties.setProperty("username", userName);
      properties.setProperty("password", password);

      Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(userName, password);
        }
      });

      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress(AppInit.fromAddress));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(AppInit.toAddress));
      message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(AppInit.ccAddress));
      message.setSubject("SFTPService : " + subject);
      message.setText(content);
      Transport.send(message);
      System.out.println("mail sent successfully....");

    catch (AddressException e) {
      e.printStackTrace();
    catch (MessagingException e) {
      e.printStackTrace();
    }

  }
}


This is SFTPConnection.java file having the source code to execute business logic.



 

    
package com.cv.sftp.key.auth;

import java.io.File;
import java.io.FileInputStream;
import java.net.URI;

import org.apache.commons.io.FileUtils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 @author Chandra Vardhan
 *
 */
public class SFTPConnection {

  public static void main(String[] args) {

    SFTPConnection fs = new SFTPConnection();
    String authMode = AppInit.authMode;
    if (authMode != null && authMode.equalsIgnoreCase("key")) {
      fs.jschKeyAuthentication();
    else {
      // fs.sendViaJschBasicAuth();
      fs.jschKeyAuthentication();
    }

  }

  public void jschKeyAuthentication() {
    JSch jsch = new JSch();
    Session session = null;
    ChannelSftp channel = null;
    try {
      if (AppInit.url == null) {
        throw new RuntimeException("Key file key not found in classpath");
      }
      URI keyFileURI = AppInit.url.toURI();
      jsch.addIdentity(new File(keyFileURI).getAbsolutePath());
      session = jsch.getSession(AppInit.keyAuthUserId, AppInit.keyAuthAddress, 22);
      if (session != null) {
        session.setServerAliveCountMax(5);
        session.setConfig("StrictHostKeyChecking""no");

        session.setTimeout(1000);
        session.setConfig("PreferredAuthentications""publickey,keyboard-interactive,password");
        try {
          session.connect();
        catch (JSchException e) {
          e.printStackTrace();
        }
        channel = (ChannelSftpsession.openChannel("sftp");
        if (channel != null) {
          channel.connect();
          try {
            File[] listOfFiles = new File(AppInit.keyAuthSourceDirectory).listFiles();
            if (listOfFiles != null && listOfFiles.length > 0) {
              channel.cd(AppInit.keyAuthDestinationDirectory);
              for (File file : listOfFiles) {
                if (file.isFile()) {
                  try {
                    channel.put(new FileInputStream(file), file.getName());
                    String backUpDir = AppInit.keyAuthBackupDirectory;
                    File backDir = new File(backUpDir);
                    if (backDir != null && !backDir.exists()) {
                      backDir.mkdirs();
                    }
                    try {
                      FileUtils.copyFileToDirectory(file, backDir);
                    catch (Exception e) {
                      EmailUtility.sendEmail("Problem while taking the file backup !!!",
                          "There is a problem while taking the file backup !!!");

                      e.printStackTrace();

                    }
                    try {
                      FileUtils.forceDelete(file);
                    catch (Exception e) {
                      EmailUtility.sendEmail("Problem while deleting the file from source",
                          "There is a problem while deleting the file from source directory.");

                      e.printStackTrace();

                    }
                  catch (Exception e) {
                    EmailUtility.sendEmail("Problem while accessing destination directory of SFTP",
                        "There is a problem while accessing the destination directory. Host IP : "
                            + AppInit.keyAuthAddress + " and User id : "
                            + AppInit.keyAuthUserId);
                    e.printStackTrace();

                  }
                }
              }
            else {
              EmailUtility.sendEmail(
                  "There are no files available in the " + AppInit.keyAuthSourceDirectory
                      " directory!!!",
                  "There are no files available in the " + AppInit.keyAuthSourceDirectory
                      " directory!!!" + AppInit.keyAuthAddress + " and User id : "
                      + AppInit.keyAuthUserId);
              System.err.println("There are no files available in the " + AppInit.keyAuthSourceDirectory
                  " directory!!!");
            }
          catch (Exception e) {
            EmailUtility.sendEmail("Problem while accessing source directory of SFTP",
                "There is a problem while accessing the Source directory. Host IP : "
                    + AppInit.keyAuthAddress + " and User id : " + AppInit.keyAuthUserId);
            e.printStackTrace();

          }
        }
      }
    catch (Exception e) {
      EmailUtility.sendEmail("Problem while connecting to SFTP",
          "There is a problem while getting the SFTP connection. Host IP : " + AppInit.keyAuthAddress
              " and User id : " + AppInit.keyAuthUserId);
      e.printStackTrace();

    finally {
      if (channel != null) {
        channel.disconnect();
      }
      if (session != null) {
        session.disconnect();
      }
    }

  }

}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.sftp.key.auth</groupId> <artifactId>SFTPConnectionWithKeyFile</artifactId> <version>1.0</version> <url>http://maven.apache.org</url> <properties> <log4j-version>1.2.17</log4j-version> 1.8 SFTPConnectionWithKeyFile </properties> <dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.42</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-vfs2</artifactId> <version>2.0</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> </dependencies> <build> <finalName>${pom.artifactId}</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> </configuration> </plugin> </plugins> </build> </project>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

No comments:

Post a Comment