Sftp連接和讀取文件

開發過程中,需求:連接到遠程sftp服務器並讀取其中的文件。

1.使用com.jcraft.jsch包中工具建立session連接遠程sftp服務器


public static Channel connect(String username, String host, int port, String password) throws JSchException {
        Session session = null;
        Channel channel = null;
        long start = System.currentTimeMillis();
        JSch jSch = new JSch();
        session = jSch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        // 設置不用檢查hostKey
        // 如果設置成“yes”,ssh就會自動把計算機的密匙加入“$HOME/.ssh/known_hosts”文件,
        // 並且一旦計算機的密匙發生了變化,就拒絕連接
        config.put("StrictHostKeyChecking", "no");
        // UseDNS選項打開狀態下,當客戶端試圖登錄OpenSSH服務器時,服務器端先根據客戶端的IP地址進行DNS PTR反向查詢,查詢出客戶端的host name,然後根據查詢出的客戶端host name進行DNS 正向A記錄查詢,驗證與其原始IP地址是否一致
        // 這是防止客戶端欺騙的一種手段,但一般我們的IP是動態的,不會有PTR記錄的,打開這個選項不過是在白白浪費時間而已。
        // 默認值是 “yes” ,爲了提高效率減少時間消耗,則把UseDNS設置爲“no”
        // 用域名訪問時纔將此選項打開
        config.put("UseDNS", "no");
        session.setConfig(config);
        session.connect(connectTimeOut);
        session.setTimeout(readTimeOut);
        channel = session.openChannel("sftp");
        channel.connect();
        long end = System.currentTimeMillis();
        info_log.info("成功登陸sftp,登陸耗時:[" + (end - start) + "]毫秒");
        return channel;
}

2.根據返回的channel列舉服務器上文件,並依次按行讀取文件內容

ChannelSftp channel = null;
try {
    //連接遠程sftp
    channel = (ChannelSftp) FtpUtil.connect(ftpUserName, ftpHost, ftpPort, ftpPasswd);

    Vector<ChannelSftp.LsEntry> ftpFiles = channel.ls(ftpRootDir);//列舉指定目錄中文件
    if (ftpFiles != null && ftpFiles.size() > 0) {
        for (LsEntry lsEntry : ftpFiles) {
            String filename = lsEntry.getFilename();
            BufferedReader bufferedReader = null;

            try {
                channel.cd(ftpRootDir);//進入指定目錄操作
                InputStream inputStream = channel.get(filename);
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                String tempString = null;
                while ((tempString = bufferedReader.readLine()) != null) {
                    //....數據處理
                }

            } catch (Exception e) {

            } finally {
                try {
                    if (bufferedReader != null)
                        bufferedReader.close();//關閉流
                } catch (IOException e) {
                    log.error("Close BufferedReader error:", e);
                }
            }               
        }
    }
            
} catch (Exception e) {
} finally {
    //記得關閉連接
    if (channel != null) {
        channel.quit();
        channel.disconnect();

        try {
            if (channel.getSession() != null)
                channel.getSession().disconnect();
                    
            } catch (JSchException e) {
                    log.error("channel getSession error:", e);
        }
}

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章