Java SFTP

SFTP

SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议。SFTP为SSH的一部份,是一种传输文件到服务器的安全加密的方式。

JSch

JSch是ssh的Java实现,从官网http://www.jcraft.com/jsch/ 下载jar包(jsch-0.1.55.jar),加入项目即可。

使用JSch连接SFTP

使用JSch连接SFTP服务器操作的步骤大致为:

  1. 使用ip、port、username、password等信息连接sftp,获取Session
  2. Session可以设置一系列属性,如超时时间等,通过Session建立链接
  3. Session建立连接后,打开SFTP通道Channel
  4. Channel连接之后便形成可用的ChannelSftp
  5. JSch封装了常用指令,如:sftp.put()、sftp.cd()、sftp.get()、sftp.ls(),可以进行操作
  6. 操作完成后,要关闭通道Channel和Session。

源码

  1. import com.jcraft.jsch.Channel;
  2. import com.jcraft.jsch.ChannelSftp;
  3. import com.jcraft.jsch.ChannelSftp.LsEntry;
  4. import com.jcraft.jsch.JSch;
  5. import com.jcraft.jsch.JSchException;
  6. import com.jcraft.jsch.Session;
  7. import com.jcraft.jsch.SftpException;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import java.io.File;
  11. import java.io.FileInputStream;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14. import java.util.Properties;
  15. import java.util.Vector;
  16. /**
  17. * SFTP Utils
  18. *
  19. */
  20. public class SFTPUtils {
  21. private static final Logger logger = LoggerFactory.getLogger(SFTPUtils.class);
  22. private static int TIMEOUT = 60000; // 超时数为一分钟,默认是0,表示没有超时数,单位毫秒
  23. private ChannelSftp sftp;
  24. public static SFTPUtils getInstance(String host, int port, String username, String password) {
  25. SFTPUtils instance = new SFTPUtils(host, port, username, password);
  26. return instance;
  27. }
  28. private SFTPUtils(String host, int port, String username, String password) {
  29. sftp = connect(host, port, username, password); // 获取连接
  30. }
  31. /**
  32. * 连接sftp服务器,创建一个sftp通道对象,通过这 个对象可以直接发送文件。
  33. *
  34. * @param host
  35. * 主机
  36. * @param port
  37. * 端口
  38. * @param username
  39. * 用户名
  40. * @param password
  41. * 密码
  42. * @return
  43. */
  44. public ChannelSftp connect(String host, int port, String username, String password) {
  45. ChannelSftp sftp = null;
  46. try {
  47. JSch jsch = new JSch();
  48. Session sshSession = jsch.getSession(username, host, port);
  49. sshSession.setPassword(password);
  50. Properties sshConfig = new Properties();
  51. sshConfig.put("StrictHostKeyChecking", "no");
  52. sshSession.setConfig(sshConfig); // 为Session对象设置properties
  53. sshSession.setTimeout(TIMEOUT); // 设置timeout时间
  54. sshSession.connect(); // 通过Session建立链接
  55. logger.info("SFTP Session connected.");
  56. Channel channel = sshSession.openChannel("sftp"); // 打开SFTP通道
  57. channel.connect(); // 建立SFTP通道的连接
  58. sftp = (ChannelSftp) channel;
  59. logger.info("Connected to " + host);
  60. } catch (Exception e) {
  61. logger.error(e.getMessage(), e);
  62. }
  63. return sftp;
  64. }
  65. /**
  66. * 上传文件
  67. *
  68. * @param directory
  69. * 上传的目录
  70. * @param uploadFile
  71. * 要上传的文件全路径
  72. */
  73. public boolean upload(String targetDirectory, String uploadFile) {
  74. try {
  75. Vector dir = sftp.ls(targetDirectory);
  76. if (dir == null) { // 如果路径不存在,则创建
  77. sftp.mkdir(targetDirectory);
  78. }
  79. sftp.cd(targetDirectory);
  80. File file = new File(uploadFile);
  81. FileInputStream fileInputStream = new FileInputStream(file);
  82. sftp.put(fileInputStream, file.getName());
  83. fileInputStream.close();
  84. return true;
  85. } catch (Exception e) {
  86. logger.error(e.getMessage(), e);
  87. return false;
  88. }
  89. }
  90. /**
  91. * 下载文件
  92. *
  93. * @param directory
  94. * 下载目录
  95. * @param downloadFile
  96. * 下载文件名
  97. * @param saveFile
  98. * 存在本地的文件全路径
  99. */
  100. public File downloadToFile(String directory, String downloadFile, String saveFile) {
  101. try {
  102. sftp.cd(directory);
  103. File file = new File(saveFile);
  104. FileOutputStream fileOutputStream = new FileOutputStream(file);
  105. sftp.get(downloadFile, fileOutputStream);
  106. fileOutputStream.close();
  107. return file;
  108. } catch (Exception e) {
  109. logger.error(e.getMessage(), e);
  110. return null;
  111. }
  112. }
  113. /**
  114. *
  115. * @param directory
  116. * 下载目录
  117. * @param downloadFile
  118. * 下载文件名
  119. * @param saveFilePath
  120. * 存在本地的路径
  121. * @return
  122. */
  123. public File downloadToDirectory(String directory, String downloadFile, String saveFilePath) {
  124. try {
  125. sftp.cd(directory);
  126. File file = new File(saveFilePath + File.separator + downloadFile);
  127. FileOutputStream fileOutputStream = new FileOutputStream(file);
  128. sftp.get(downloadFile, fileOutputStream);
  129. fileOutputStream.close();
  130. return file;
  131. } catch (Exception e) {
  132. logger.error(e.getMessage(), e);
  133. return null;
  134. }
  135. }
  136. /**
  137. * 下载文件
  138. *
  139. * @param downloadFilePath
  140. * 下载的文件完整目录
  141. * @param saveFile
  142. * 存在本地的路径
  143. */
  144. public File download(String downloadFilePath, String saveFile) {
  145. try {
  146. int i = downloadFilePath.lastIndexOf('/');
  147. if (i == -1)
  148. return null;
  149. sftp.cd(downloadFilePath.substring(0, i));
  150. File file = new File(saveFile);
  151. FileOutputStream fileOutputStream = new FileOutputStream(file);
  152. sftp.get(downloadFilePath.substring(i + 1), fileOutputStream);
  153. fileOutputStream.close();
  154. return file;
  155. } catch (Exception e) {
  156. logger.error(e.getMessage(), e);
  157. return null;
  158. }
  159. }
  160. /**
  161. * 关闭会话和通道
  162. */
  163. public void disconnect() {
  164. try {
  165. sftp.getSession().disconnect();
  166. } catch (JSchException e) {
  167. logger.error(e.getMessage(), e);
  168. }
  169. sftp.quit();
  170. sftp.disconnect();
  171. }
  172. /**
  173. * 列出目录下的文件
  174. *
  175. * @param directory
  176. * 要列出的目录
  177. * @throws SftpException
  178. */
  179. public Vector<LsEntry> listFiles(String directory) throws SftpException {
  180. return sftp.ls(directory);
  181. }
  182. public static void main(String[] args) throws IOException {
  183. Logger logger = LoggerFactory.getLogger(SFTPUtils.class);
  184. String host = "zhangzhiqiang.net";
  185. int port = 22;
  186. String username = "silent";
  187. String password = "Citic123!";
  188. // 服务器端可供操作的目录
  189. String serverDirectory = "/upload";
  190. SFTPUtils sf = null;
  191. try {
  192. sf = SFTPUtils.getInstance(host, port, username, password);
  193. sf.upload(serverDirectory, "C:\\Users\\waiti\\Desktop\\b.xls"); // 上传文件
  194. sf.downloadToFile(serverDirectory, "b.java", "C:\\Users\\waiti\\Desktop\\b3.java");
  195. sf.downloadToDirectory(serverDirectory, "b.java", "C:\\Users\\waiti\\Desktop");
  196. Vector<LsEntry> files = sf.listFiles(serverDirectory); // 查看文件列表
  197. if (files != null) {
  198. for (LsEntry file : files) {
  199. System.out.println(file.getFilename());
  200. }
  201. }
  202. } catch (SftpException e) {
  203. logger.error("SFTP Error!", e);
  204. } finally {
  205. if (sf != null) {
  206. sf.disconnect();
  207. }
  208. }
  209. }
  210. }
欣赏此文?求鼓励,求支持!您的支持就是支持我更新的最大动力!
表情 | 预览
Powered By Valine
v1.3.10