π Problem
You need to connect to and manage multiple SFTP servers in Java using the JSch library, where each server uses private key authentication (with or without a passphrase). You also want to perform file operations on each server during the same program execution.
π Solution Overview
We'll use the JSch (Java Secure Channel) library to:
- Load the appropriate private key.
- Establish SFTP sessions per server.
- Perform SFTP file operations.
- Cleanly disconnect after use.
π¦ Step 1: Add the JSch Dependency
If you're using Maven, add this to your pom.xml
:
xml
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
π§βπ» Step 2: Java Code to Handle Multiple SFTP Servers
java
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.util.Properties;
public class SFTPManager {
// β
Connect to a single SFTP server using a private key
public static ChannelSftp connectToSFTP(String username, String host, int port, String privateKeyPath, String passphrase) throws Exception {
JSch jsch = new JSch();
jsch.addIdentity(privateKeyPath, passphrase); // null if no passphrase
Session session = jsch.getSession(username, host, port);
// π Bypass host key confirmation for simplicity
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
// π‘ Open and return SFTP channel
ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
return channel;
}
public static void main(String[] args) {
try {
// π Define details for multiple SFTP servers
String[][] sftpServers = {
{"username1", "host1.example.com", "22", "/path/to/privateKey1", "passphrase1"},
{"username2", "host2.example.com", "22", "/path/to/privateKey2", "passphrase2"}
};
// π Loop through each server and perform operations
for (String[] server : sftpServers) {
String username = server[0];
String host = server[1];
int port = Integer.parseInt(server[2]);
String privateKeyPath = server[3];
String passphrase = server[4];
ChannelSftp sftp = connectToSFTP(username, host, port, privateKeyPath, passphrase);
System.out.println("β
Connected to " + host);
// π Perform your file operations here
// Example: sftp.put("/local/file.txt", "/remote/dir/file.txt");
// β Disconnect cleanly
sftp.disconnect();
sftp.getSession().disconnect();
System.out.println("π Disconnected from " + host);
}
} catch (Exception e) {
System.err.println("β Error connecting to SFTP server: " + e.getMessage());
e.printStackTrace();
}
}
}
π§ͺ Example Output
css
β
Connected to host1.example.com
π Disconnected from host1.example.com
β
Connected to host2.example.com
π Disconnected from host2.example.com
π Key Concepts
ConceptPurposejsch.addIdentity(path, passphrase)
Loads the private key for authenticationsession.setConfig(...)
Skips manual key verification (not for production without security checks)channelSftp.put(...)
Upload file (can also use get
, ls
, cd
, etc.)loop through server configs
Scales the solution to manage many servers
π‘οΈ Security Notes
- β
Use proper key permissions (
chmod 600
for PEM files). - π Avoid setting
"StrictHostKeyChecking"
to "no"
in productionβuse known_hosts
. - π§Ύ Consider logging errors and successes per host.
π Possible Enhancements
- Store server configs in a
JSON
or .properties
file. - Wrap SFTP operations into a utility/service class.
- Add retry logic and timeout handling.
- Use connection pooling for frequent use.