基于scp协议向linux发送文件

基于scp协议向linux发送文件的优点:
1.不需要linux服务器安装其他组件
2.可以再linux任意路劲下操作文件
3.但是需要开通scp权限

准备条件:
jar包:
ganymed-ssh2-build210.jar
maven依赖:

<!-- https://mvnrepository.com/artifact/ch.ethz.ganymed/ganymed-ssh2 -->
<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>build210</version>
</dependency>

首先写一个基本操作的demo
注:只提供通过ip、用户名、密码 连接linux服务的方式
基本测试用的demo(亲测):

package com.spongeli;

import java.io.IOException;

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

public class DEMO {
    public static void main(String[] args) {
        int port = 22;
        String hostname = "192.168.245.131";
        String username = "root";
        String password = "spongeli";
        //1.0  创建连接
        Connection connection = new Connection(hostname, port);
        //2.0 获取连接
        try {
            connection.connect();
            //3.0 验证用户名密码
            boolean flag = connection.authenticateWithPassword(username, password);
            if(!flag){
                throw new Exception("用户名、密码错误!");
            }
            // 4.0 获取SCP客户端连接(用于操作上传下载文件)
            //SCPClient client = new SCPClient(connection);
            // 4.1 上传文件
            //String localFile = "e:\\test5.xlsx";   //本地文件目录
            //String targetDest = "/";              //上传目录  "/" 用户的家目录
            //client.put(localFile, targetDest);
            //System.out.println("123");
            //下载
            //client.get("/test5.xlsx", "d://");

            //5.0 操作服务器文件
            /*5.1  建立一个SFTP客户端 */        
            SFTPv3Client sftpClient = new SFTPv3Client(connection);
            //创建一个文件
            /*String fileName = "/abc";
            sftpClient.createFile(fileName );*/
            //创建一个目录
            //sftpClient.mkdir("/dir", 0600);
            //删除一个空目录
            //sftpClient.rmdir("/dir");
            //删除文件
            sftpClient.rm("/abc");
        } catch (IOException e) {
            System.out.println("获取连接异常");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

封装工具类:
特点:封装了一个可以创建多层目录的方法,createFile,正常的提供的方法,只容许在父目录存在的情况下,创建子目录

package com.spongeli.utils;

import java.io.IOException;

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

public class ScpClientManager {

    private String ip ;
    private int port ;
    private String username ;
    private String password ;
    private static ScpClientManager instance;

    public static synchronized  ScpClientManager getInstance(String ip, int port,
            String username, String password) {
        if (instance == null) {
            instance = new ScpClientManager(ip, port, username, password);
        }
        return instance;
    }
    private ScpClientManager(String ip, int port,
            String username, String password){
        this.ip = ip ;
        this.username = username;
        this.port = port ;
        this.password = password ;
    }
    /***
     * 
     * @param remoteFile 需要下载的文件
     * @param localTargetDirectory 下载到本地的目录
     * @throws Exception 
     */
    public void getFile(String remoteFile, String localTargetDirectory) throws Exception {
        Connection conn = new Connection(ip,port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username,
                    password);
            if (isAuthenticated == false) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            client.get(remoteFile, localTargetDirectory);
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new Exception();
        }finally {
            if(conn != null){
                conn.close();
            }
         }
    }
    /**
     * 上传文件至指定目录
     * @param localFile 需要上传的本地文件  
     * @param remoteTargetDirectory  目标服务器的地址
     * @throws Exception 
     */
    public void putFile(String localFile, String remoteTargetDirectory) throws Exception {
        Connection conn = new Connection(ip,port);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username,
                    password);
            if (isAuthenticated == false) {
                System.err.println("authentication failed");
            }
            SCPClient client = new SCPClient(conn);
            client.put(localFile, remoteTargetDirectory);
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new Exception();
        }finally {
            if(conn != null){
                conn.close();
            }
         }
    }
    /**
     * 删除一个空的目录。。注意 空的  如果非空 删除失败
     * @param destDir
     * @throws Exception 
     */
    public void deleteDir(String destDir) throws Exception{
         Connection conn = new Connection(ip,port);
         try {
             conn.connect();
             boolean isAuthenticated = conn.authenticateWithPassword(username,
                     password);
             if (isAuthenticated == false) {
                 System.err.println("authentication failed");
             }
             /* 建立一个SFTP客户端 */        
             SFTPv3Client sftpClient = new SFTPv3Client(conn);
             if(destDir!=null&&destDir.length()>0){
                 destDir = destDir.replaceAll("\\\\", "/");
             }
             sftpClient.rmdir(destDir);

         } catch (IOException ex) {
            ex.printStackTrace();
            throw new Exception();
         }finally {
            if(conn != null){
                conn.close();
            }
         }
    }
    /**
     * 在远程linux 服务器 删除文件
     * @param destFile 目标文件
     * @throws Exception 
     */
    public void deleteFile(String destFile) throws Exception{
         Connection conn = new Connection(ip,port);
         try {
             conn.connect();
             boolean isAuthenticated = conn.authenticateWithPassword(username,
                     password);
             if (isAuthenticated == false) {
                 System.err.println("authentication failed");
             }
             /* 建立一个SFTP客户端 */        
             SFTPv3Client sftpClient = new SFTPv3Client(conn);
             sftpClient.rm(destFile);

         } catch (IOException ex) {
            ex.printStackTrace();
            throw new Exception();
         }finally {
            if(conn != null){
                conn.close();
            }
         }
    }
    /***
     * 在远程linux服务器   创建目录
     * 默认权限是0600 表示可读写
     * @param directory 必须以/开头和/结尾
     * @throws Exception 
     */
    public void createFile(String directory) throws Exception{
        System.out.println("---需要创建目标目录---:"+directory);
        if(directory != null && directory.length()>0){
            directory = directory.replaceAll("\\\\","/");
            if(directory.startsWith("/") && directory.endsWith("/")){
                Connection conn = new Connection(ip,port);
                try {
                    conn.connect();
                    boolean isAuthenticated = conn.authenticateWithPassword(username,
                            password);
                    if (isAuthenticated == false) {
                        System.err.println("authentication failed");
                    }
                    /* 建立一个SFTP客户端 */        
                    SFTPv3Client sftpClient = new SFTPv3Client(conn);
                    StringBuffer sb = new StringBuffer();
                    /* 开始切割目录  */
                    directory = directory.substring(1, directory.length()-1);
                    String[] split = directory.split("/");
                    /* 循环创建目录 */
                    for (int i = 0; i < split.length; i++) {
                        sb.append("/"+split[i]);
                        try {
                            sftpClient.ls(sb.toString());
                        } catch (Exception e) {
                            sftpClient.mkdir(sb.toString(), 0600);
                        }
                    }
                    conn.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }else{
                throw new Exception("所传路径个是不合法!");
            }
        }else{
            throw new Exception("所传路径为空!");
        }
    }
    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

工具调用测试:

package com.spongeli.test;

import com.spongeli.utils.ScpClientManager;

public class Test {
    public static void main(String[] args) {
        String ip = "192.168.245.131";
        String username = "root";
        String password = "spongeli";
        int port = 22;
        ScpClientManager manager = ScpClientManager.getInstance(ip, port, username, password);
        try {
            /*创建目录*/
            //manager.createFile("\\usr/tmp/a/b/c/d\\");
            /*删除空目录*/
            //manager.deleteDir("/usr/tmp/a/b\\c");
            /*删除文件 */
            //manager.deleteFile("/var/tmp/a/b/a.txt");
            /* 下载 文件 */
            //manager.getFile("/var/tmp/a/b/全.txt", "E:\\sql");
            /* 上传 文件  */
            manager.putFile("E:\\junqi.jgs", "/");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值