java实现从windows传到linux

最近的项目可能会要求从Windows远程传输文件到Linux环境下,实现方式很多

本文采用ganymed-ssh2-build210.jar

package cn.uid5a;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

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

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.1.111";//替换成目标IP
            int port = 22;
            String username = "root";
            String password = "ab123cd564";
            Scpclient client = Scpclient.getInstance(IP, port, username, password);
            //默认会连接到home/users目录下
            client.upload("/apache-maven-3.5.0-bin.zip", "./");
//            client.getAllFile(file, tmp);
            //client.upload("/Users/yyx/Downloads/mac.sh", "maccpoy.sh", "./Public", null);
            //client.download("/home/master/mac.sh", "/Users/yyx/Downloads/test");
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

福海鑫森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值