1. 程式人生 > >java 通過SFTP連線,獲取指定目錄檔案和上傳檔案

java 通過SFTP連線,獲取指定目錄檔案和上傳檔案

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;

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


public class SftpClientUtil {



    /**
     * 密碼方式登入 讀取指定目錄檔案
     *
     * @param ip
     * @param user
     * @param psw
     * @param port
     */
    public static File[]  sshSftpReadFile(String ip, String user, String psw, int port, String sPath) {
        Session session = null;
        File[] targetFiles =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);

            targetFiles = readFile(session,sPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    return targetFiles;
    }

    /**
     * 密碼方式登入 上傳指定檔案到指定目錄
     *
     * @param ip
     * @param user
     * @param psw
     * @param port
     */
    public static File sshSftpUpLoadFile(String ip, String user, String psw, int port, String sPath,File file) {
        Session session = null;
        File folderToScan = 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(session,file,sPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return folderToScan;
    }

    public static  File[] readFile(Session session, String sPath) {

        Channel channel = null;
        File folderToScan = null;
        File[] targetFiles =null;
        try {
            channel = (Channel) session.openChannel("sftp");
            channel.connect(10000000);
            ChannelSftp sftp = (ChannelSftp) channel;
            try {
                sftp.cd(sPath);

            } catch (SftpException e) {

                sftp.mkdir(sPath);
                sftp.cd(sPath);

            }
            folderToScan = new File(sPath);
            targetFiles = folderToScan.listFiles();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.disconnect();
            channel.disconnect();
        }
        return targetFiles;
    }


    public static void upLoadFile(Session session,  File file , String sPath) {

        Channel channel = null;
        try {
            channel = (Channel) session.openChannel("sftp");
            channel.connect(10000000);
            ChannelSftp sftp = (ChannelSftp) channel;
            try {
                sftp.cd(sPath);
                //
            } catch (SftpException e) {

                sftp.mkdir(sPath);
                sftp.cd(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);
                    sftp.mkdir(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 < list.length; i++) {
                copyFile(sftp, list[i], pwd);
            }
        } else {

            try {
                sftp.cd(pwd);

            } catch (SftpException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            InputStream instream = null;
            OutputStream outstream = null;
            try {
                outstream = sftp.put(file.getName());
                instream = new FileInputStream(file);

                byte b[] = new byte[1024];
                int n;
                try {
                    while ((n = instream.read(b)) != -1) {
                        outstream.write(b, 0, n);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } catch (SftpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    outstream.flush();
                    outstream.close();
                    instream.close();

                } catch (Exception e2) {
                    // TODO: handle exception
                    e2.printStackTrace();
                }
            }
        }
    }

 /**
     * 密匙方式登入
     * 
     * @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();
        }
    }

}