package com.yutou.tools.utils;

import com.jcraft.jsch.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ListIterator;
import java.util.Properties;

public class SFTPTools {
    private static SFTPTools tools;
    Session sshSession = null;
    ChannelSftp sftp = null;
    public static SFTPTools getInstance(){
        if(tools==null){
            try {
                tools=new SFTPTools();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return tools;
    }

    private SFTPTools() throws Exception {
        JSch jsch = new JSch();
        sshSession = jsch.getSession("yutou", "113.109.20.210", 23);
        sshSession.setPassword("34864394");
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp) channel;
        sftp.cd("/media/yutou/disk_lvm/public/");
    }
    /**
     * 删除
     */
    public void delete(String directory, String deleteFile) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 上传
     */
    public void upload(String directory, String uploadFile) {
        try {
            sftp.cd(directory);
            File file = new File(uploadFile);
            sftp.put(new FileInputStream(file), file.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载
     */
    public void download(String directory, String downloadFile, String saveFile) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));//可以用流
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //https://www.cnblogs.com/nlpvv/articles/11244553.html
    public void getPath() {
        try {
            for (Object o : sftp.ls("/media/yutou/disk_lvm/public/")) {
                ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) o;
                System.out.println(entry.getFilename() + " size=" + entry.getAttrs().getSize()+" "+entry.getAttrs().isDir());
            }
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
    public void close(){
        sftp.disconnect();
        sftp.exit();
        sftp.quit();
        sshSession.disconnect();
    }

    public static void main(String[] args) {
        try {
            SFTPTools tools=new SFTPTools();
            tools.getPath();
            tools.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
