Uploading a file to a remote server using JSch’s SFTP functionality can be achieved by leveraging the JSch library, which is a Java implementation of the SSH2 protocol. Here’s an example of how you can upload a file to a remote server with JSch:
Steps to Follow:
- Create a
JSch
instance to manage the SSH communication. - Establish an SFTP session by connecting to the server with the correct credentials (host, port, username, password, etc.).
- Open the SFTP channel.
- Transfer the file using the
put
method within the SFTP channel.
Example Code
Below is a full example of uploading a file to a remote server:
package org.kodejava.jsch;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.File;
public class SFTPFileUpload {
public static void main(String[] args) {
String remoteHost = "sftp.example.com";
int port = 22; // Default port for SSH
String username = "username";
String password = "password";
String localFilePath = "C:/path/to/local/file.txt"; // File to upload
String remoteDir = "/remote/directory/"; // Remote directory (including trailing '/')
Session session = null;
ChannelSftp channelSftp = null;
try {
// Initialize JSch
JSch jsch = new JSch();
// Create an SSH session
session = jsch.getSession(username, remoteHost, port);
session.setPassword(password);
// Configure session - optionally disable strict host key checking
session.setConfig("StrictHostKeyChecking", "no");
// Connect to the remote server
System.out.println("Connecting to the SFTP server...");
session.connect();
System.out.println("Connected to the SFTP server.");
// Open an SFTP channel
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
System.out.println("SFTP channel opened.");
// Upload the file
File localFile = new File(localFilePath);
if (localFile.exists() && localFile.isFile()) {
channelSftp.put(localFilePath, remoteDir + localFile.getName());
System.out.println("File uploaded successfully.");
} else {
System.err.println("Local file not found or is not a file.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Cleanup and disconnect the session and channel
if (channelSftp != null && channelSftp.isConnected()) {
channelSftp.disconnect();
System.out.println("SFTP channel disconnected.");
}
if (session != null && session.isConnected()) {
session.disconnect();
System.out.println("Session disconnected.");
}
}
}
}
Explanation of the Code
Session
Creation:- Use
JSch
to create a session withusername
,remoteHost
, andport
. - Set the user’s password and configure optional settings like disabling host key verification.
- Use
- Establish Connection:
session.connect()
establishes the connection with the server over SSH.
- Open SFTP Channel:
- By opening an SFTP channel (
session.openChannel("sftp")
), you can perform file-related operations.
- By opening an SFTP channel (
- File Upload:
- The
put
method withinChannelSftp
uploads the file. - The first parameter is the file path of the local file.
- The second parameter defines the destination path (including filename).
- The
- Resource Cleanup:
- You must disconnect the channel and session once operations are completed to release resources.
Key Points
- Make sure to provide proper permissions to the remote folder for the user you’re authenticating as.
- Handle exceptions and inputs securely, especially when dealing with credentials and file access.
- Use strict host key checking in production to avoid man-in-the-middle attacks (consider using a
known_hosts
file and not disablingStrictHostKeyChecking
).
This example should help you upload files effortlessly using JSch and SFTP.
Maven Dependencies
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>