SFTP connection using 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 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");
    }
  }

  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 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) {
                      e.printStackTrace();
                    }

                  catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              }
            else {

              System.err.println("There are no files available in the " + AppInit.keyAuthSourceDirectory
                  " directory!!!");
            }
          catch (Exception e) {

            e.printStackTrace();

          }
        }
      }
    catch (Exception e) {

      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>SFTPConnectionUsingKeyFile</artifactId> <version>1.0</version> <url>http://maven.apache.org</url> <properties> <log4j-version>1.2.17</log4j-version> 1.8 SFTPConnectionUsingKeyFile </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

1 comment: