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

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

本文采用ganymed-ssh2-build210.jar,官网:http://www.ganymed.ethz.ch/ssh2/

 

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");
        }
}

 

通过Jsch连接
step 1引入jar包
<!-- jcraft包 -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency>

step 2 代码
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class Main {
    public static void main(String[] args) throws Exception {
        long currentTimeMillis = System.currentTimeMillis();

        String command = "uname -a";
 
        JSch jsch = new JSch();
        Session session = jsch.getSession("xfraud", "192.168.115.64", 22);
        session.setPassword("cfca1234");
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(60 * 1000);
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
 
        channel.setInputStream(null);
 
        ((ChannelExec) channel).setErrStream(System.err);
 
        InputStream in = channel.getInputStream();
 
        channel.connect();
 
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0) continue;
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
 
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("Jsch方式"+(currentTimeMillis1-currentTimeMillis));
    }

}
 

 

 

通过ganymed-ssh2连接
step 1 引入jar包
<dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>

</dependency>

step 2 代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

//import org.apache.commons.lang.StringUtils;

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

public class MainCommand {
    private static String DEFAULTCHART = "UTF-8";

    private static Connection login(String ip, String username, String password) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = new Connection(ip);
            connection.connect();// 连接
            flag = connection.authenticateWithPassword(username, password);// 认证
            if (flag) {
                System.out.println("================登录成功==================");
                return connection;
            }
        } catch (IOException e) {
            System.out.println("=========登录失败=========" + e);
            connection.close();
        }
        return connection;
    }

    /**
     * 远程执行shll脚本或者命令
     * 
     * @param cmd
     *            即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    private static String execmd(Connection connection, String cmd) {
        String result = "";
        try{
            if (connection != null) {
                Session session = connection.openSession();// 打开一个会话
                session.execCommand(cmd);// 执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                System.out.println(result);
                // 如果为得到标准输出为空,说明脚本执行出错了
                /*if (StringUtils.isBlank(result)) {
                    System.out.println("得到标准输出为空,链接conn:" + connection + ",执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                } else {
                    System.out.println("执行命令成功,链接conn:" + connection + ",执行的命令:" + cmd);
                }*/
                connection.close();
                session.close();
            }
        } catch (IOException e) {
            System.out.println("执行命令失败,链接conn:" + connection + ",执行的命令:" + cmd + "  " + e);
            e.printStackTrace();
        }
        return result;

    }

    /**
     * 解析脚本执行返回的结果集
     * 
     * @param in
     *            输入流对象
     * @param charset
     *            编码
     * @return 以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
                System.out.println(line);
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            System.out.println("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        long currentTimeMillis = System.currentTimeMillis();
        String ip = "192.168.115.64";
        String username = "xfraud";
        String password = "cfca1234";
        String cmd = "uname -a";        
        Connection connection = login(ip, username, password);
        String execmd = execmd(connection, cmd);
        System.out.println(execmd);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("ganymed-ssh2方式"+(currentTimeMillis1-currentTimeMillis));
    }
}

运行结果比较


可以看出采用ganymed-ssh2连接方式要快很多。
--------------------- 
作者:风间净琉璃 
来源:CSDN 
原文:https://blog.csdn.net/u011937566/article/details/81666347 
 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

福海鑫森

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

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

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

打赏作者

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

抵扣说明:

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

余额充值