一、下載sftp軟件
1、百度雲快速下載
下載sftp軟件,我用的版本是:1.3.1,
鏈接:https://pan.baidu.com/s/12TCh9a3YevUOpVLVrx2VWg
提取碼:65xh
複製這段內容後打開百度網盤手機App,操作更方便哦
2、進入官網下載
http://www.freesshd.com/,然後點擊Download,下載freeSSHd.exe,目前最新的就是1.3.1
二、安裝sftp服務器
1、運行freeSSHd.exe(最好以管理員方式運行)
2、選擇安裝位置,這裏我沒改,使用默認位置C:\Program Files (x86)\freeSSHd
3、這裏選擇要安裝的內容, 只有一個選項,全部安裝,沒得選,😄
4、這裏選擇開始欄程序所在的文件夾名稱,這裏默認,如果你不想創建開始啓動欄快捷入口,可以選中左下角的複選框,這裏我沒選
5、這裏是是否創建桌面快捷方式,默認是創建,如果你不需要,則取消選中,這裏我使用默認選中
6、這一步是讓你對你安裝過程中選擇的進行查看確認,如果有和你想的不一致的,可以退回重新設置,如果沒問題,則開始安裝
7、安裝進行中ing
8、安裝過程會彈出這個窗口,直接關閉即可
9、提示“提示私有祕鑰沒安裝”,點擊確認,安裝目錄下會多出幾個文件
安裝密鑰前:
安裝密鑰後:
10、這裏提示是否把freeSSHd作爲一個服務安裝到服務中,這裏我不選作爲服務安裝:
11、安裝完成。
三、配置sftp服務器
1、添加用戶
2、設置SSH服務器ip,端口等信息
3、設置登錄授權選項,其中Public key auth意指通過公鑰登錄
4、設置sftp服務器根目錄
5、啓動服務器Server Status,這裏我們只用到sftp,所以只啓動sftp
四、cmd命令行測試
1、登錄測試連接 注:sftp命令默認端口22, 完整命令是:sftp -P 22 [email protected],可簡寫sftp [email protected]
輸入:yes
輸入密碼:test123
常見問題:
測試連接時遇到如下問題,刪除當前登錄用戶下的.ssh文件夾,再使用管理員程序重新運行freesshd,再次測試連接
異常及解決方案
輸入正確用戶名和密碼提示denied或者key verification failed.,常規解決方案如下
1. 刪除C:\Users\Administrator下的.ssh文件夾,使用管理員程序重新運行freesshd,再次測試連接
2、使用cmd命令上傳下載文件
上傳格式:put+空格+要上傳的文件路徑+空格+根目錄後的相對路徑
上傳:put d:/file.txt /upload
例如這裏是把d盤下的file.txt上傳到F:\sftp_dir\upload,其中F:\sftp_dir是根目錄
下載格式:get+空格+要下載相對跟目錄的文件路徑+空格+文件下載的位置
下載:get /download/download.txt e:/
例如這裏是把F:\sftp_dir\download\download.txt下載到e盤根目錄,其中F:\sftp_dir是根目錄
五、java代碼測試sftp
1、工具類SFTPUtil.java
package com.acconsys.chs.CHSService.util;
import java.io.ByteArrayOutputStream;
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.util.Properties;
import java.util.Vector;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
/**
* 類說明 sftp工具類
*/
public class SFTPUtil {
private ChannelSftp sftp;
private Session session;
/** SFTP 登錄用戶名*/
private String username;
/** SFTP 登錄密碼*/
private String password;
/** 私鑰 */
private String privateKey;
/** SFTP 服務器地址IP地址*/
private String host;
/** SFTP 端口*/
private int port;
/**
* 構造基於密碼認證的sftp對象
*/
public SFTPUtil(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
/**
* 構造基於祕鑰認證的sftp對象
*/
public SFTPUtil(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}
public SFTPUtil(){}
/**
* 連接sftp服務器
*/
public void login(){
try {
JSch jsch = new JSch();
if (privateKey != null) {
jsch.addIdentity(privateKey);// 設置私鑰
}
session = jsch.getSession(username, host, port);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
// session.setConfig("userauth.gssapi-with-mic", "no");
// session.setConfig("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
}
/**
* 關閉連接 server
*/
public void logout(){
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
}
}
}
/**
* 將輸入流的數據上傳到sftp作爲文件。文件完整路徑=basePath+directory
* @param basePath 服務器的基礎路徑
* @param directory 上傳到該目錄
* @param sftpFileName sftp端文件名
* @param in 輸入流
*/
public void upload(String basePath,String directory, String sftpFileName, InputStream input) throws SftpException{
try {
sftp.cd(basePath);
sftp.cd(directory);
} catch (SftpException e) {
//目錄不存在,則創建文件夾
String [] dirs=directory.split("/");
String tempPath=basePath;
for(String dir:dirs){
if(null== dir || "".equals(dir)) continue;
tempPath+="/"+dir;
try{
sftp.cd(tempPath);
}catch(SftpException ex){
sftp.mkdir(tempPath);
sftp.cd(tempPath);
}
}
}
sftp.put(input, sftpFileName); //上傳文件
}
/**
* 下載文件。
* @param directory 下載目錄
* @param downloadFile 下載的文件
* @param saveFile 存在本地的路徑
*/
public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
}
/**
* 下載文件
* @param directory 下載目錄
* @param downloadFile 下載的文件名
* @return 字節數組
*/
public byte[] download(String directory, String downloadFile) throws SftpException, IOException{
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream is = sftp.get(downloadFile);
byte[] fileData = toByteArray(is);
return fileData;
}
private static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
/**
* 刪除文件
* @param directory 要刪除文件所在目錄
* @param deleteFile 要刪除的文件
*/
public void delete(String directory, String deleteFile) throws SftpException{
sftp.cd(directory);
sftp.rm(deleteFile);
}
/**
* 列出目錄下的文件
* @param directory 要列出的目錄
* @param sftp
*/
public Vector<?> listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
//上傳文件測試
public static void main(String[] args) throws SftpException, IOException, DocumentException {
SFTPUtil sftp = new SFTPUtil("test", "test123", "localhost", 22);
sftp.login();
File file = new File("C:\\Users\\35725\\Downloads\\shujujiegouJavajhkj_jb51\\數據結構和Java集合框架.pdf");
InputStream is = new FileInputStream(file);
sftp.upload("/sftp_dir","/upload", "2.pdf", is);
// System.out.println(sftp.listFiles("/data_export/test"));
// Vector<?> files = sftp.listFiles("/data_export/test");
// for(Object f:files){
// LsEntry entry = (LsEntry)f;
// System.out.println(entry.getFilename());
// System.out.println(entry.getLongname());
// SftpATTRS atts = entry.getAttrs();
//
// }
// File file = new File("C:\\Documents and Settings\\huangyuchi\\Desktop\\00CHS\\jdk1.6.zip");
// InputStream is = new FileInputStream(file);
// sftp.upload("/data_export", "/test", "jdk1.6.zip", is);
//// byte[] bs = sftp.download("/data_export/CHSFileExchange", "將字符串.xml");
// byte[] bs = sftp.download("/data_export/CHSFileExchange", "將字符串.xml");
// sftp.download("/data_export/CHSFileExchange", "將字符串.xml" ,"D://將字符串.xml");
// System.out.println(new String(bs,"utf-8"));
// String result = "";
// Document document = DocumentHelper.parseText(new String(bs,"utf-8")); // 將字符串轉爲XML
// String status = document.getRootElement().element("message").element("status").getText();
// String errors = document.getRootElement().element("message").element("errors").getText();
// String reviewStatus = document.getRootElement().element("message").element("ReviewStatus").getText();
// if(status.equals("successful") && !"NO".equals(reviewStatus)){
// result = status;//lca成功,預審籤成功
// }else if(status.equals("successful") && "NO".equals(reviewStatus)){
// //lca成功,預審籤失敗
// result = status+" "+errors+" "+reviewStatus;
// }else{
// //全部失敗
// result = status+" "+errors;
// }
// System.out.println("result is " + result);
sftp.logout();
}
}
六、卸載sftp
參考