ftp服务器和sftp服务器

首先,ftp跟sftp是一种传输协议,一种安全,一种不安全。其中经过实践发现要有相对于的服务器才能实现上传跟下载,不能混淆使用。
windows中ftp服务器的建立方法:第一种:系统自带的ftp
开启服务:
这里写图片描述
建立ftp,映射地址和文件夹
这里写图片描述
新建用户和密码访问ftp
这里写图片描述

贴上java类的测试代码:

package com.test;

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

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FileTool {  

    /** 
     * Description: 向FTP服务器上传文件 
     * @Version      1.0 
     * @param url FTP服务器hostname 
     * @param port  FTP服务器端口 
     * @param username FTP登录账号 
     * @param password  FTP登录密码 
     * @param path  FTP服务器保存目录 
     * @param filename  上传到FTP服务器上的文件名 
     * @param input   输入流 
     * @return 成功返回true,否则返回false * 
     */  
    public static boolean uploadFile(String url,// FTP服务器hostname  
            int port,// FTP服务器端口  
            String username, // FTP登录账号  
            String password, // FTP登录密码  
            String path, // FTP服务器保存目录  
            String filename, // 上传到FTP服务器上的文件名  
            InputStream input // 输入流  
    ){  
        boolean success = false;  
        FTPClient ftp = new FTPClient();  
        ftp.setControlEncoding("GBK");  
        try {  
            int reply;  
            ftp.connect(url, port);// 连接FTP服务器  
            // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
            ftp.login(username, password);// 登录  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                return success;  
            }  
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);  
            ftp.makeDirectory(path);  
            ftp.changeWorkingDirectory(path);  
            ftp.storeFile(filename, input);  
            input.close();  
            ftp.logout();  
            success = true;  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch (IOException ioe) {  
                }  
            }  
        }  
        return success;  
    }  

    /** 
     * 将本地文件上传到FTP服务器上 * 
     */  
    public static void upLoadFromProduction(String url,// FTP服务器hostname  
            int port,// FTP服务器端口  
            String username, // FTP登录账号  
            String password, // FTP登录密码  
            String path, // FTP服务器保存目录  
            String filename, // 上传到FTP服务器上的文件名  
            String orginfilename // 输入流文件名  
       ) {  
        try {  
            FileInputStream in = new FileInputStream(new File(orginfilename));  
            boolean flag = uploadFile(url, port, username, password, path,filename, in);  
            System.out.println(flag);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
     //测试  
    public static void main(String[] args) {  

        upLoadFromProduction("127.0.0.1", 21, "cl", "123456", "/", "gggg.txt", "E:/错误日志.txt");  
    }  
}  

第二种:利用Apache的ftp,下载地址:https://download.csdn.net/download/qq_35807697/10358750
修改两个配置文件
这里写图片描述
这里写图片描述
这里写图片描述

启动命令:
这里写图片描述
java测试代码

package com.test;

import it.sauronsoftware.ftp4j.FTPClient;  
import java.security.SecureRandom;  
import java.security.cert.X509Certificate;  
import javax.net.ssl.SSLContext;  
import javax.net.ssl.SSLSocketFactory;  
import javax.net.ssl.TrustManager;  
import javax.net.ssl.X509TrustManager; 

public class Ftp4jTest {  
    public static void main(String[] args) {  
        try {  
            TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {  
                public X509Certificate[] getAcceptedIssuers() {  
                    return null;  
                }  
                public void checkClientTrusted(X509Certificate[] certs,  
                        String authType) {  
                }  
                public void checkServerTrusted(X509Certificate[] certs,  
                        String authType) {  
                }  
            } };  
            SSLContext sslContext = null;  
            sslContext = SSLContext.getInstance("SSL");  
            //sslContext = SSLContext.getDefault();  
            sslContext.init(null, trustManager, new SecureRandom());  
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();  
            FTPClient client = new FTPClient();  
            client.setSSLSocketFactory(sslSocketFactory);  
            client.setSecurity(FTPClient.SECURITY_FTPES);   
            client.connect("127.0.0.1", 22);  
            client.login("cl", "123456");  
            System.out.println(client.toString());  
            System.out.println(client.currentDirectory());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
} 

第三种:安装sftp服务器,下载地址:https://download.csdn.net/download/xx5595480/9406498
下载软件,然后就是安装完成配置服务器。
这里写图片描述

这里写图片描述
这里写图片描述
java测试代码:

package com.test;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class SFTPProcessor {
    private static Session session = null;
    private static ChannelSftp channel = null;



    public static ChannelSftp getConnect() {
       /*String ftpHost = "192.168.100.120";
         String port = "21";
         String ftpUserName = "ftptest";
         String ftpPassword = "ftptest";*/


         String ftpHost = "192.168.100.120";
         String port = "22";
         String ftpUserName = "ftptest";
         String ftpPassword = "ftptest";

         //默认的端口22 此处我是定义到常量类中;
         int ftpPort = 22;
         //判断端口号是否为空,如果不为空,则赋值
         if (port != null && !port.equals("")) {
             ftpPort = Integer.valueOf(port);
         }
         JSch jsch = new JSch(); // 创建JSch对象
         // 按照用户名,主机ip,端口获取一个Session对象
         try {
              session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
              if (ftpPassword != null) {
               session.setPassword(ftpPassword); // 设置密码
              }
              String ftpTO="20000";
              if (!(ftpTO==null||"".equals(ftpTO))) {
                  int ftpTimeout=Integer.parseInt(ftpTO);
                  session.setTimeout(ftpTimeout); // 设置timeout时候
              }
              //并且一旦计算机的密匙发生了变化,就拒绝连接。
              session.setConfig("StrictHostKeyChecking", "no");
              //默认值是 “yes” 此处是由于我们SFTP服务器的DNS解析有问题,则把UseDNS设置为“no”
              session.setConfig("UseDNS", "no");
              session.connect(); // 经由过程Session建树链接
              channel = (ChannelSftp) session.openChannel("sftp"); // 打开SFTP通道
              channel.connect(); // 建树SFTP通道的连接
         } catch (JSchException e) {
          // TODO Auto-generated catch block
             e.printStackTrace();
         }
         return channel;
    }

    public static void closeChannel() throws Exception {
         try {
              if (channel != null) {
                  channel.disconnect();
              }
              if (session != null) {
                  session.disconnect();
              }
         } catch (Exception e) {
              throw new Exception( "close ftp error.");
         }
    }


    public static void uploadFile(String localFile, String newName, String remoteFoldPath) throws Exception{
         InputStream input = null;
         try {
            input = new FileInputStream(new File(localFile));
          // 改变当前路径到指定路径 
          channel.cd(remoteFoldPath);
          channel.put(input, newName);
         } catch (Exception e) {
          throw new Exception( "Upload file error.");
         } finally {
          if (input != null) {
           try {
            input.close();
           } catch (IOException e) {
            throw new Exception("Close stream error.");
           }
          }
         }
    }


    public void downloadFile(String remoteFile, String remotePath, String localFile) throws Exception {
         OutputStream output = null;
         File file = null;
         try {
              file = new File(localFile);
              if (!checkFileExist(localFile)) {
               file.createNewFile();
              }
              output = new FileOutputStream(file);
              channel.cd(remotePath);
              channel.get(remoteFile, output);
         } catch (Exception e) {
              throw new Exception("Download file error.");
         } finally {
              if (output != null) {
                   try {
                       output.close();
                   } catch (IOException e) {
                       throw new Exception("Close stream error.");
                   }
              }

         }
    }


    @SuppressWarnings("unchecked")
    public Vector listFiles(String remotePath) throws Exception {
         Vector vector = null;
         try {
          vector = channel.ls(remotePath);
         } catch (SftpException e) {
          throw new Exception("list file error.");
         }
         return vector;
    }


    private boolean checkFileExist(String localPath) {
         File file = new File(localPath);
         return file.exists();
    }

    public static void main(String[] args) throws Exception {

        SFTPProcessor ftpUtil = new SFTPProcessor();
        System.out.println("开始连接");
        ChannelSftp channeltest = ftpUtil.getConnect();
        System.out.println("开始连接");

        System.out.println(channeltest.isConnected());
        ftpUtil.downloadFile("cussplus_3.5.0.1.zip.001", "/opt/applog/msiUpdate/Kiosk/3.7/COMMON/PEK", "E:\\projectTest\\downloadPath\\cussplus_3.5.0.1.zip.001");
        ftpUtil.closeChannel();
        System.out.println(channeltest.isConnected());
        System.out.println("结束连接连接");

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值