scp实现OS之间的远程传输文件

1 篇文章 0 订阅

问题场景

最近的项目可能会要求从Windows远程传输文件到Linux环境下,实现方式很多,本文采用ganymed-ssh2-build210.jar。支持递归上传与下载文件夹的例子请参照我的另一篇博客sftp实现OS之间的远程传输文件与文件夹

code

package scp;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by yangyouxing
 * date on 2017/5/13.
 */
public class Scpclient {

    private static Scpclient instance;

    public static synchronized Scpclient getInstance(String IP, int port, String username, String password) {

        if (instance == null) {
            instance = new Scpclient(IP, port, username, password);
        }
        return instance;
    }

    public Scpclient(String IP, int port, String username, String password) {
        this.ip = IP;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    /**
     * 下载单个文件
     * @param remoteFile            /home/master/mac.sh
     * @param localTargetDirectory  /Users/yyx/Downloads/test (must exist)
     */
    public void download(String remoteFile, String localTargetDirectory) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (!isAuthenticated) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            client.get(remoteFile, localTargetDirectory);
            conn.close();
        } catch (IOException ex) {
            Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 上传单个文件,且支持上传单个文件夹下所有文件(不包括目录结构)
     * @param localFile                 /Users/yyx/Downloads/mac.sh or /Users/yyx/Downloads/mac
     * @param remoteTargetDirectory     /home/master/ (must exist)
     */
    public void upload(String localFile, String remoteTargetDirectory) {
        upload(localFile, remoteTargetDirectory, null);
    }

    /**
     * 上传单个文件,且支持上传单个文件夹下所有文件(不包括目录结构)
     * @param localFile                 /Users/yyx/Downloads/mac.sh or /Users/yyx/Downloads/mac
     * @param remoteTargetDirectory     /home/master/ (must exist)
     * @param mode                      0600 = 'rw- --- ---'
     */
    public void upload(String localFile, String remoteTargetDirectory, String mode) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (!isAuthenticated) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            File file = new File(localFile);
            List<String> list = new ArrayList<>();
            getAllFile(file, list);
            String[] files = new String[list.size()];
            list.toArray(files);
            if((mode == null) || (mode.length() == 0)){
                mode = "0600";
            }
            client.put(files, remoteTargetDirectory, mode);
            conn.close();
        } catch (IOException ex) {
            Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * 递归获取文件
     * @param file  file or dir
     * @return      List<String>
     */
    private void getAllFile(File file, List<String> tmp) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                getAllFile(files[i], tmp);
            }
        } else  {
            tmp.add(file.getAbsolutePath());
        }
    }

    /**
     * 上传单个文件并重命名该文件
     * @param localFile             /Users/yyx/Downloads/mac.sh
     * @param remoteFileName        copy.sh
     * @param remoteTargetDirectory /home/master/
     * @param mode                  0600 = 'rw- --- ---'
     */
    public void upload(String localFile, String remoteFileName, String remoteTargetDirectory, String mode) {
        Connection conn = new Connection(ip, port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (!isAuthenticated) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            if((mode == null) || (mode.length() == 0)){
                mode = "0600";
            }
            client.put(localFile, remoteFileName, remoteTargetDirectory, mode);

            //rename
            Session session = conn.openSession();
            String tmpPathName = remoteTargetDirectory + File.separator + remoteFileName;
            String newPathName = tmpPathName.substring(0, tmpPathName.lastIndexOf("."));
            session.execCommand("mv " + remoteFileName + " " + newPathName);//重命名回来

            conn.close();
        } catch (IOException ex) {
            Logger.getLogger(SCPClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private String ip;
    private int port;
    private String username;
    private String password;

    public static void main(String[] args) {
        String IP = "192.168.***.***";//替换成目标IP
        int port = 22;
        String username = "master";
        String password = "master";
        Scpclient client = Scpclient.getInstance(IP, port, username, password);
        //默认会连接到home/users目录下
        client.upload("/Users/yyx/Downloads/android_upload.zip", "./");
        //client.upload("/Users/yyx/Downloads/mac.sh", "maccpoy.sh", "./Public", null);
        //client.download("/home/master/mac.sh", "/Users/yyx/Downloads/test");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值