J2SSH - SFTP Client Connectivity

Making the connection
Reading a file
Sending Files
Deleting Files or Directories
Creating a Directory
Creating Nested Directories
Renaming Files
Changing permissions on files


Introduction

SFTP is an interactive file transfer protocol which performs all operations over the SSH transport, it is a replacement for the original SCP (Secure Copy) protocol that existed in SSH1. It is highly recommended that SFTP be used to perform file transfers in preference to the legacy FTP protocol as authentication details are transmitted in plain-text format with the latter, and as such may be compromised through "password sniffing" attacks.

The following J2SSH namespace must be imported into a class wishing to incorporate SFTP functionality:

import com.sshtools.j2ssh.SftpClient;

Making the connection
In order to transfer files through SFTP, you must first open an SftpClient connection from a connected and authenticated SshClient object. This will initialise the SFTP subsystem for usage.

SftpClient sftp = ssh.openSftpClient();

Reading a file
In order to read a file you should use the get method of the SftpClient.

// Copy the file to the local computer
sftp.get("temp.exe", "c:/temp.exe");

Sending Files

Use the put command to send files to the server.

// Sends a file to the remote server
sftp.put("c:/temp.exe", "/root/temp.exe");

Deleting Files or Directories

Use the rm command to delete files or empty directories.

sftp.rm(authorizationFile + ".bak");

Creating a Directory

Use the mkdir command to create a new directory, the new directory will be placed in the current SFTP directory.

sftp.mkdir("newdir");

Creating Nested Directories

You can use the mkdirs command to create nested directory structure quickly. This method will create any directories that are not present in the directory path parameter.

// Creates four new nested directories in one go
sftp.mkdirs("/root/new/new2/new3/new4");

Renaming Files

To rename a file or directory use the rename command on the SftpClient object.

 sftp.rename("FromName.txt", "ToName.txt");

Changing Permissions on Files

In order to change permissions associated with files, we use the chmod method of the SftpClient class to specify permissions in an octal format. The relevant octal values are listed below.

sftp.chmod(666, "/root/temp.exe");

Absolute modes are octal numbers specifying the complete list of attributes for the files. You specify attributes by OR'ing together these bits:

01000000 temporary file
02000000 compressed file
4000 Hidden file (setuid bit)
2000 System file (setgid bit)
1000 Archive bit (sticky bit)
0400 Individual read
0200 Individual write
0100 Individual execute (or list directory)
0040 Group read
0020 Group write
0010 Group execute
0004 Other read
0002 Other write
0001 Other execute