Use SFTP protocol to transfer files securely in java

file

This article describes how to use SSH-based file transfer protocol (SFTP) in Java to upload files from the local to a remote server, or to transfer files securely between two servers. Let’s take a look at these agreements first

  • SSH is a more reliable protocol designed to provide security for remote login sessions and other network services. For example: the cloud server we purchased uses ssh when logging in.
  • The ftp protocol is usually used to transfer files between two servers, but it is inherently insecure.
  • So what is SFTP? SFTP can be understood as SSH + FTP, which is a secure network file transfer protocol.

Generally speaking, SFTP and FTP services use corresponding client software to provide services. If you want to use SFTP protocol for secure file transfer in java code, then this article is for you.

1. Import JSch dependency package

Import the following coordinates in the maven project pom.xml, we use JSch, JSch encapsulates the SFTP protocol into the corresponding API for us to call.

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

2. File transfer – JSch example

2.1 get and put methods

In JSch, we can use putand gettransfer files between servers. putThe method is used to transfer files from the local system to the remote server.

channelSftp.put(localFile, remoteFile);

getThe method downloads the file from the remote server to the local system.

channelSftp.get(remoteFile, localFile);

2.2 Use username and password for authentication

JSch jsch = new JSch();
jsch.setKnownHosts("/home/zimug/.ssh/known_hosts");
jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

jschSession.setPassword(PASSWORD);
  • "/home/zimug/.ssh/known_hosts" is the known_hosts file of SSH, which is the public key save file of the trusted remote host.
  • USERNAME is the username
  • REMOTE_HOST remote host IP
  • REMOTE_PORT remote host port
  • PASSWORD remote host login password

2.3. Use public and private keys for authentication

If readers cannot understand the usage and meaning of public and private keys, they need to supplement their SSH knowledge first.

  • Local private key –/home/登录用户名/.ssh/id_rsa
  • The default storage location of the remote public key –~/.ssh/authorized_keys
JSch jsch = new JSch();
jsch.setKnownHosts("/home/zimug/.ssh/known_hosts");
jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

jsch.addIdentity("/home/zimug/.ssh/id_rsa");

2.4 JSchExample of complete file transfer

Transfer files from the local system to the remote server 1.2.3.4, and use the SSH password login method for authentication.

import com.jcraft.jsch.*;

public class SFTPFileTransfer {

    private static final String REMOTE_HOST = "1.2.3.4";  //远程主机ip
    private static final String USERNAME = "";  //登录用户名
    private static final String PASSWORD = "";  //登陆密码
    private static final int REMOTE_PORT = 22;   //ssh协议默认端口
    private static final int SESSION_TIMEOUT = 10000; //session超时时间
    private static final int CHANNEL_TIMEOUT = 5000; //管道流超时时间

    public static void main(String[] args) {

        String localFile = "/home/zimug/local/random.txt";   //本地文件路径
        String remoteFile = "/home/zimug/remote/targetfile.txt";   //上传到远程的文件路径,要保证登录用户有写权限

        Session jschSession = null;

        try {

            JSch jsch = new JSch();
            jsch.setKnownHosts("/home/zimug/.ssh/known_hosts");
            jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

            // 通过ssh私钥的方式登录认证
            // jsch.addIdentity("/home/zimug/.ssh/id_rsa");

            // 通过密码的方式登录认证
            jschSession.setPassword(PASSWORD);
            jschSession.connect(SESSION_TIMEOUT);

            Channel sftp = jschSession.openChannel("sftp");  //建立sftp文件传输管道
            sftp.connect(CHANNEL_TIMEOUT);

            ChannelSftp channelSftp = (ChannelSftp) sftp;

            // 传输本地文件到远程主机
            channelSftp.put(localFile, remoteFile);

            channelSftp.exit();

        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        } finally {
            if (jschSession != null) {
                jschSession.disconnect();
            }
        }
        System.out.println("文件传输完成!");
    }
}

3. JSch exception handling

During the file upload process, we may encounter some of the following exceptions

3.1UnknownHostKey exception

The IP address of the remote server needs to be added to the known_hostsfile.

$ ssh-keyscan -t rsa 1.2.3.4 >> ~/.ssh/known_hosts

3.2 Invalid exception for private key

It is possible that the remote server has regenerated the private key, and the private key distribution needs to be copied to the local server.

ssh-copy-id  -i  ~/.ssh/id_rsa.pub  <被分发的服务器ip>

3.3 For Auth failexceptions

Please ensure that the login password provided is correct

com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(Session.java:519)
    at com.zimug.io.howto.SFTPFileTransfer.main(SFTPFileTransfer.java:34)

Welcome to follow my blog, there are many boutique collections

  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

If you think it is helpful to you, please like and share it for me! Your support is my inexhaustible creative motivation! . In addition, the author has output the following high-quality content recently, and I look forward to your attention.

Guess you like

Origin blog.csdn.net/hanxiaotongtong/article/details/109020499