sftp


package net.xwolf.ultility;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException; public class FtpImpl{
   
   
private String host = "127.0.0.1";
   
private String username="MingMac";
   
private String password="×××";
   
private int port = 22;
   
private ChannelSftp sftp = null;
   
private String localPath = "/Users/MingMac/Documents";
   
private String remotePath = "/Users/MingMac/MyDocuments";
   
private String fileListPath = "/Users/MingMac/Documents/Java/workspace/MyTools/conf/file.txt";
   
private final String seperator = "/";
   
   
/**
     * connect server via sftp
    
*/
   
public void connect() {
       
try {
           
if(sftp != null){
                System.out.println(
"sftp is not null");
            }
            JSch jsch
= new JSch();
            jsch.getSession(username, host, port);
            Session sshSession
= jsch.getSession(username, host, port);
            System.out.println(
"Session created.");
            sshSession.setPassword(password);
            Properties sshConfig
= new Properties();
            sshConfig.put(
"StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            System.out.println(
"Session connected.");
            System.out.println(
"Opening Channel.");
            Channel channel
= sshSession.openChannel("sftp");
            channel.connect();
            sftp
= (ChannelSftp) channel;
            System.out.println(
"Connected to " + host + ".");
        }
catch (Exception e) {
            e.printStackTrace();
        }
    }
   
/**
     * Disconnect with server
    
*/
   
public void disconnect() {
       
if(this.sftp != null){
           
if(this.sftp.isConnected()){
               
this.sftp.disconnect();
            }
else if(this.sftp.isClosed()){
                System.out.println(
"sftp is closed already");
            }
        }

    }

   
public void download() {
       
// TODO Auto-generated method stub
       

    }
   
   
   
private void download(String directory, String downloadFile,String saveFile, ChannelSftp sftp) {
       
try {
            sftp.cd(directory);
            File file
= new File(saveFile);
            sftp.get(downloadFile,
new FileOutputStream(file));
        }
catch (Exception e) {
            e.printStackTrace();
        }
    }
   
   
/**
     * upload all the files to the server
    
*/
   
public void upload() {
        List
<String> fileList = this.getFileEntryList(fileListPath);
       
try {
           
if(fileList != null){
               
for (String filepath : fileList) {
                    String localFile
= this.localPath + this.seperator+ filepath;
                    File file
= new File(localFile);
                   
                   
if(file.isFile()){
                        System.out.println(
"localFile : " + file.getAbsolutePath());
                        String remoteFile
= this.remotePath + this.seperator + filepath;
                        System.out.println(
"remotePath:" + remoteFile);
                        File rfile
= new File(remoteFile);
                        String rpath
= rfile.getParent();
                       
try {
                            createDir(rpath, sftp);
                        }
catch (Exception e) {
                            System.out.println(
"*******create path failed" + rpath);
                        }

                       
this.sftp.put(new FileInputStream(file), file.getName());
                        System.out.println(
"=========upload down for " + localFile);
                    }
                }
            }
        }
catch (FileNotFoundException e) {
           
// TODO Auto-generated catch block
            e.printStackTrace();
        }
catch (SftpException e) {
           
// TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
   
/**
     * create Directory
     *
@param filepath
     *
@param sftp
    
*/
   
private void createDir(String filepath, ChannelSftp sftp){
       
boolean bcreated = false;
       
boolean bparent = false;
        File file
= new File(filepath);
        String ppath
= file.getParent();
       
try {
           
this.sftp.cd(ppath);
            bparent
= true;
        }
catch (SftpException e1) {
            bparent
= false;
        }
       
try {
           
if(bparent){
               
try {
                   
this.sftp.cd(filepath);
                    bcreated
= true;
                }
catch (Exception e) {
                    bcreated
= false;
                }
               
if(!bcreated){
                   
this.sftp.mkdir(filepath);
                    bcreated
= true;
                }
               
return;
            }
else{
                createDir(ppath,sftp);
               
this.sftp.cd(ppath);
               
this.sftp.mkdir(filepath);
            }
        }
catch (SftpException e) {
            System.out.println(
"mkdir failed :" + filepath);
            e.printStackTrace();
        }
       
       
try {
           
this.sftp.cd(filepath);
        }
catch (SftpException e) {
            e.printStackTrace();
            System.out.println(
"can not cd into :" + filepath);
        }
       
    }
   
/**
     * get all the files need to be upload or download
     *
@param file
     *
@return
    
*/
   
private List<String> getFileEntryList(String file){
        ArrayList
<String> fileList = new ArrayList<String>();
        InputStream in
= null;
       
try {
           
            in
= new FileInputStream(file);
            InputStreamReader inreader
= new InputStreamReader(in);
           
            LineNumberReader linreader
= new LineNumberReader(inreader);
            String filepath
= linreader.readLine();
           
while(filepath != null){
                fileList.add(filepath);
                filepath
= linreader.readLine();
            }
            in.close();
        }
catch (FileNotFoundException e) {
           
// TODO Auto-generated catch block
            e.printStackTrace();
        }
catch (IOException e) {
           
// TODO Auto-generated catch block
            e.printStackTrace();
        }
finally{
           
if(in != null){
                in
= null;
            }
        }

       
return fileList;
    }

   
/**
     *
@return the host
    
*/
   
public String getHost() {
       
return host;
    }

   
/**
     *
@param host the host to set
    
*/
   
public void setHost(String host) {
       
this.host = host;
    }

   
/**
     *
@return the username
    
*/
   
public String getUsername() {
       
return username;
    }

   
/**
     *
@param username the username to set
    
*/
   
public void setUsername(String username) {
       
this.username = username;
    }

   
/**
     *
@return the password
    
*/
   
public String getPassword() {
       
return password;
    }

   
/**
     *
@param password the password to set
    
*/
   
public void setPassword(String password) {
       
this.password = password;
    }

   
/**
     *
@return the port
    
*/
   
public int getPort() {
       
return port;
    }

   
/**
     *
@param port the port to set
    
*/
   
public void setPort(int port) {
       
this.port = port;
    }

   
/**
     *
@return the sftp
    
*/
   
public ChannelSftp getSftp() {
       
return sftp;
    }

   
/**
     *
@param sftp the sftp to set
    
*/
   
public void setSftp(ChannelSftp sftp) {
       
this.sftp = sftp;
    }

   
/**
     *
@return the localPath
    
*/
   
public String getLocalPath() {
       
return localPath;
    }

   
/**
     *
@param localPath the localPath to set
    
*/
   
public void setLocalPath(String localPath) {
       
this.localPath = localPath;
    }

   
/**
     *
@return the remotePath
    
*/
   
public String getRemotePath() {
       
return remotePath;
    }

   
/**
     *
@param remotePath the remotePath to set
    
*/
   
public void setRemotePath(String remotePath) {
       
this.remotePath = remotePath;
    }

   
/**
     *
@return the fileListPath
    
*/
   
public String getFileListPath() {
       
return fileListPath;
    }

   
/**
     *
@param fileListPath the fileListPath to set
    
*/
   
public void setFileListPath(String fileListPath) {
       
this.fileListPath = fileListPath;
    }
   
   
public static void main(String[] args) {
       
// TODO Auto-generated method stub
        FtpImpl ftp= new FtpImpl();
        ftp.connect();
        ftp.upload();
        ftp.disconnect();
        System.exit(
0);
    }


}

### SFTP 协议及其使用方法 SFTP(Secure File Transfer Protocol,安全文件传输协议)是一种通过 SSH 提供的安全网络协议。它用于在网络上进行安全的文件传输操作。以下是关于 SFTP 的一些重要概念以及其实现方式。 #### 什么是 SFTPSFTP 是一种基于 SSH 的协议,旨在提供更高级别的安全性来替代传统的 FTP。与 FTP 不同的是,SFTP 使用加密技术保护数据在网络上传输时不会被窃听或篡改[^2]。 #### 实现 SFTP 文件传输的方法 在 Java 中可以通过 JSch 库实现 SFTP 功能。JSch 是一个纯 Java 编写的 SSH2 协议库,支持多种功能,包括但不限于端口转发、X11 转发和文件传输等。下面是一个简单的代码示例展示如何利用 JSch 进行基本的 SFTP 操作: ```java import com.jcraft.jsch.*; public class SFTPDemo { public static void main(String[] args) { String host = "your.sftp.server"; int port = 22; String username = "username"; String password = "password"; try { JSch jsch = new JSch(); Session session = jsch.getSession(username, host, port); session.setPassword(password); // Disable StrictHostKeyChecking to avoid UnknownHostException java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; // Upload file example sftpChannel.put("/path/to/local/file.txt", "/path/to/remote/directory/"); // Download file example sftpChannel.get("/path/to/remote/file.txt", "/path/to/local/directory/"); sftpChannel.exit(); session.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 此代码片段展示了如何建立 SFTP 连接并执行文件上传和下载的操作。需要注意的是,在实际应用中应避免硬编码密码,并考虑启用更强的身份验证机制如公钥认证[^2]。 #### 安全注意事项 当部署涉及敏感信息的应用程序时,务必遵循最佳实践以保障通信链路的安全性。这可能包括但不限于配置防火墙规则限制访问范围、定期轮换密钥材料以及监控异常活动日志记录行为等措施。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值