热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

java实现sftp客户端上传文件以及文件夹的功能代码

1.依赖的jar文件 jsch-0.1.53.jar 2.登录方式有密码登录,和密匙登录  代码: 主函数: im

1.依赖的jar文件 jsch-0.1.53.jar

2.登录方式有密码登录,和密匙登录

 代码:

主函数:

import java.util.Properties;

import com.cloudpower.util.Login;
import com.util.LoadProperties;

public class Ftp {
  public static void main(String[] args) {
    Properties properties = LoadProperties.getProperties();
    Login.login(properties);
  }
}

登陆页面的代码:

package com.cloudpower.util;

import java.io.Console;
import java.util.Properties;

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

public class Login {

  public static void login(Properties properties) {
    String ip = properties.getProperty("ip");
    String user = properties.getProperty("user");
    String pwd = properties.getProperty("pwd");
    String port = properties.getProperty("port");
    String privateKeyPath = properties.getProperty("privateKeyPath");
    String passphrase = properties.getProperty("passphrase");
    String sourcePath = properties.getProperty("sourcePath");
    String destinatiOnPath= properties.getProperty("destinationPath");

    if (ip != null && !ip.equals("") && user != null && !user.equals("")
        && port != null && !port.equals("") && sourcePath != null
        && !sourcePath.equals("") && destinationPath != null
        && !destinationPath.equals("")) {

      if (privateKeyPath != null && !privateKeyPath.equals("")) {
        sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath,
            passphrase, sourcePath, destinationPath);
      } else if (pwd != null && !pwd.equals("")) {
        sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath,
            destinationPath);
      } else {
        Console cOnsole= System.console();
        System.out.print("Enter password:");
        char[] readPassword = console.readPassword();
        sshSftp(ip, user, new String(readPassword),
            Integer.parseInt(port), sourcePath, destinationPath);
      }
    } else {
      System.out.println("请先设置配置文件");
    }
  }

  /**
   * 密码方式登录
   * 
   * @param ip
   * @param user
   * @param psw
   * @param port
   * @param sPath
   * @param dPath
   */
  public static void sshSftp(String ip, String user, String psw, int port,
      String sPath, String dPath) {
    System.out.println("password login");
    Session session = null;

    JSch jsch = new JSch();
    try {
      if (port <= 0) {
        // 连接服务器,采用默认端口
        session = jsch.getSession(user, ip);
      } else {
        // 采用指定的端口连接服务器
        session = jsch.getSession(user, ip, port);
      }

      // 如果服务器连接不上,则抛出异常
      if (session == null) {
        throw new Exception("session is null");
      }

      // 设置登陆主机的密码
      session.setPassword(psw);// 设置密码
      // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
      session.setConfig("StrictHostKeyChecking", "no");
      // 设置登陆超时时间
      session.connect(300000);
      UpLoadFile.upLoadFile(session, sPath, dPath);
    } catch (Exception e) {
      e.printStackTrace();
    }

    System.out.println("success");
  }

  /**
   * 密匙方式登录
   * 
   * @param ip
   * @param user
   * @param port
   * @param privateKey
   * @param passphrase
   * @param sPath
   * @param dPath
   */
  public static void sshSftp2(String ip, String user, int port,
      String privateKey, String passphrase, String sPath, String dPath) {
    System.out.println("privateKey login");
    Session session = null;
    JSch jsch = new JSch();
    try {
      // 设置密钥和密码
      // 支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了
      if (privateKey != null && !"".equals(privateKey)) {
        if (passphrase != null && "".equals(passphrase)) {
          // 设置带口令的密钥
          jsch.addIdentity(privateKey, passphrase);
        } else {
          // 设置不带口令的密钥
          jsch.addIdentity(privateKey);
        }
      }
      if (port <= 0) {
        // 连接服务器,采用默认端口
        session = jsch.getSession(user, ip);
      } else {
        // 采用指定的端口连接服务器
        session = jsch.getSession(user, ip, port);
      }
      // 如果服务器连接不上,则抛出异常
      if (session == null) {
        throw new Exception("session is null");
      }
      // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
      session.setConfig("StrictHostKeyChecking", "no");
      // 设置登陆超时时间
      session.connect(300000);
      UpLoadFile.upLoadFile(session, sPath, dPath);
      System.out.println("success");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

文件上传的代码:

package com.cloudpower.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class UpLoadFile {
  public static void upLoadFile(Session session, String sPath, String dPath) {

    Channel channel = null;
    try {
      channel = (Channel) session.openChannel("sftp");
      channel.connect(10000000);
      ChannelSftp sftp = (ChannelSftp) channel;
      try {
        sftp.cd(dPath);
        Scanner scanner = new Scanner(System.in);
        System.out.println(dPath + ":此目录已存在,文件可能会被覆盖!是否继续y/n&#63;");
        String next = scanner.next();
        if (!next.toLowerCase().equals("y")) {
          return;
        }

      } catch (SftpException e) {

        sftp.mkdir(dPath);
        sftp.cd(dPath);

      }
      File file = new File(sPath);
      copyFile(sftp, file, sftp.pwd());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      session.disconnect();
      channel.disconnect();
    }
  }

  public static void copyFile(ChannelSftp sftp, File file, String pwd) {

    if (file.isDirectory()) {
      File[] list = file.listFiles();
      try {
        try {
          String fileName = file.getName();
          sftp.cd(pwd);
          System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName);
          sftp.mkdir(fileName);
          System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);
        } catch (Exception e) {
          // TODO: handle exception
        }
        pwd = pwd + "/" + file.getName();
        try {

          sftp.cd(file.getName());
        } catch (SftpException e) {
          // TODO: handle exception
          e.printStackTrace();
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      for (int i = 0; i 

读取配置文件的代码:

package com.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LoadProperties {
  public static Properties getProperties() {

    File file = new File(Class.class.getClass().getResource("/").getPath()
        + "properties.properties");

    InputStream inputStream = null;

    try {
      inputStream = new FileInputStream(file);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    Properties properties = new Properties();
    try {
      properties.load(inputStream);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return properties;

  }
}

代码目录结构:

测试运行时配置文件放在项目的bin目录下(打包成可运行jar文件的时候要删除,打包完成后将配置文件和jar包放在同级目录下即可):

properties.properties

ip=
user=
pwd=
port=22
privateKeyPath=
passphrase=
sourcePath=
destinatiOnPath=/home/dbbs/f

打包可运行jar文件:

Export->java->Runnabe JAR file

完成后

在控制台运行java -jar  导出jar包的名字.jar 即可

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
  • c# java socketn 字节流_C#Socket编程详解(一)TCP与UDP简介
    一、TCP与UDP(转载)1、TCP1.1定义TCP(TransmissionControlProtocol)传输控制协议。是一种可靠的、面向连接的协议(eg:打电话)、传输效率低 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • Linux服务器密码过期策略、登录次数限制、私钥登录等配置方法
    本文介绍了在Linux服务器上进行密码过期策略、登录次数限制、私钥登录等配置的方法。通过修改配置文件中的参数,可以设置密码的有效期、最小间隔时间、最小长度,并在密码过期前进行提示。同时还介绍了如何进行公钥登录和修改默认账户用户名的操作。详细步骤和注意事项可参考本文内容。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 如何在服务器主机上实现文件共享的方法和工具
    本文介绍了在服务器主机上实现文件共享的方法和工具,包括Linux主机和Windows主机的文件传输方式,Web运维和FTP/SFTP客户端运维两种方式,以及使用WinSCP工具将文件上传至Linux云服务器的操作方法。此外,还介绍了在迁移过程中需要安装迁移Agent并输入目的端服务器所在华为云的AK/SK,以及主机迁移服务会收集的源端服务器信息。 ... [详细]
  • LVS实现负载均衡的原理LVS负载均衡负载均衡集群是LoadBalance集群。是一种将网络上的访问流量分布于各个节点,以降低服务器压力,更好的向客户端 ... [详细]
  • 大坑|左上角_pycharm连接服务器同步写代码(图文详细过程)
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了pycharm连接服务器同步写代码(图文详细过程)相关的知识,希望对你有一定的参考价值。pycharm连接服务 ... [详细]
  • 概述H.323是由ITU制定的通信控制协议,用于在分组交换网中提供多媒体业务。呼叫控制是其中的重要组成部分,它可用来建立点到点的媒体会话和多点间媒体会议 ... [详细]
  • POCOCLibraies属于功能广泛、轻量级别的开源框架库,它拥有媲美Boost库的功能以及较小的体积广泛应用在物联网平台、工业自动化等领域。POCOCLibrai ... [详细]
  • 现在比较流行使用静态网站生成器来搭建网站,博客产品着陆页微信转发页面等。但每次都需要对服务器进行配置,也是一个重复但繁琐的工作。使用DockerWeb,只需5分钟就能搭建一个基于D ... [详细]
  • 在单位的一台4cpu的服务器上部署了esxserver,挂载了6个虚拟机,目前运行正常。在安装部署过程中,得到了cnvz.net论坛精华区 ... [详细]
  • UDP千兆以太网FPGA_verilog实现(四、代码前期准备UDP和IP协议构建)
    UDP:userDatagramprotocol用户数据报协议无连接的传输层协议,提供面向事务的简单不可靠信息传送服务,IETFRFC76 ... [详细]
  • SQL Server 2008 到底需要使用哪些端口?
    SQLServer2008到底需要使用哪些端口?-下面就来介绍下SQLServer2008中使用的端口有哪些:  首先,最常用最常见的就是1433端口。这个是数据库引擎的端口,如果 ... [详细]
  • 三、寻找恶意IP并用iptables禁止掉找出恶意连接你的服务器80端口的IP,直接用iptables来drop掉它;这里建议写脚本来运行, ... [详细]
  • HTTP协议相关的网络经典五层模型
    网络通信相关概念的讲解–网络协议分层(经典五层模型)在我们了解HTTP相关内容之前我们先来了解一下“网络协议分层”相关内容,因为这个是我们了解HTTP相关内容的前提条件;大家有一 ... [详细]
author-avatar
mobiledu2502853323
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有