Use Apache Mina SSHD :: SFTP to implement remote file operations in Java
Use Apache Mina SSHD :: SFTP to implement remote file operations in Java
Overview
Apache Mina SSHD is a Java -based SSH server implementation. It provides a set of API to achieve the SSH server and client function in Java applications.This article will introduce how to use Apache Mina SSHD :: SFTP library to achieve remote file operations in Java, including uploading, downloading, deleting and renamed operations.
SFTP (SSH FILE Transfer Protocol) is a sub -protocol for the SSH protocol that is used for safe file transmission between remote hosts and local hosts.It provides similar features to FTP, but transmits data through SSH security channels to ensure the confidentiality and integrity of the data.
Step 1: Add dependencies
First of all, we need to add Apache Mina SSHD :: SFTP dependencies in the construction file (such as maven's pom.xml).Add the following code to the DependenCies part:
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-sftp</artifactId>
<version>2.7.0</version>
</dependency>
Step 2: Create the SSH server
We first need to create a SSH server so that other clients can be connected to it through SSH.The following is an example code for creating the SSH server:
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.UserAuthPasswordFactory;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;
import java.io.IOException;
public class SftpServerExample {
public static void main(String[] args) throws IOException {
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(22);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
sshd.setPasswordAuthenticator((username, password, session) -> "password".equals(password));
sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory.Builder().build()));
sshd.start();
}
}
In the above example, we created a default SSH server instance and specified the server's port number (default 22).We also set a simple password authenticator to verify whether the user name and password in the connection request match whether the user name and password match the expected value.Here is a hard -coding password verification method. In the production environment, more secure methods should be used, such as user vouchers stored in the database.
Step 3: Write the SFTP client code
In our Java applications or other clients, we can use Apache Mina SSHD :: SFTP library to connect and operate remote files.The following is a simple example code. How to use the SFTP client upload file to the remote server:
import org.apache.sshd.common.scp.ScpTransferEventListener;
import org.apache.sshd.common.scp.ScpTransferEventListenerAdapter;
import org.apache.sshd.common.scp.ScpTransferEvent;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelSession;
import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.client.sftp.SftpClient;
import org.apache.sshd.client.sftp.SftpClientFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SftpClientExample {
public static void main(String[] args) throws IOException {
SshClient sshClient = SshClient.setUpDefaultClient();
sshClient.start();
try (ChannelSession session = sshClient.openSession().checkedGet()) {
session.start();
SftpClient sftpClient = SftpClientFactory.instance().createSftpClient(session);
Path localFile = Paths.get("/path/to/local/file.txt");
String remoteDirectory = "/path/to/remote/directory";
String remoteFile = "file.txt";
sftpClient.mkdirs(remoteDirectory);
sftpClient.upload(localFile, remoteDirectory + "/" + remoteFile);
sftpClient.close();
System.out.println("File uploaded successfully!");
} finally {
sshClient.stop();
}
}
}
In the above example, we first create an SSH client instance and connect to the remote SSH server.We then use the SFTP client factory to create an SFTP client instance.
Next, we designate the path of the local file and the path of the remote directory and upload the local files to the remote server.We use the `mkdirt () method to create a remote directory (if not exist), and use the` UPLOAD () method to upload the local files to the remote directory.
Finally, we close the SFTP client and the SSH client and print the news of successful uploading.
Other operations, such as downloading files, delete files, and renamed files, we can use the corresponding methods provided by the SFTP client to implement.
in conclusion
This article introduces how to use Apache Mina SSHD :: SFTP library to achieve remote file operations in Java.You can use the above example code as the starting point, and use the SFTP client to upload, download, delete and rename the files in your application.Please note that this is just a simple example. In actual situation, you may need more detailed error handling and log records.