Java利用ssh协议实现本地文件到远程Linux服务器的上传。

相对于文件的下载,上传就好多了,至少可以获得本地文件的绝对路径。那么就可以遍历文件目录,实现文件或者文件夹得上传。话不多说,直接代码。

一:主类

 
  1. import java.util.Properties;

  2.  
  3. import com.cloudpower.util.Login;

  4. import com.util.LoadProperties;

  5.  
  6. public class Ftp {

  7. public static void main(String[] args) {

  8. Properties properties = LoadProperties.getProperties();

  9. Login.login(properties);

  10.  
  11. }

  12. }

二:连接服务器的方式

 
  1. package com.cloudpower.util;

  2.  
  3. import java.io.Console;

  4. import java.util.Properties;

  5.  
  6. import com.jcraft.jsch.JSch;

  7. import com.jcraft.jsch.Session;

  8.  
  9. public class Login {

  10. /**

  11. *

  12. * @param ip 服务器IP

  13. * @param user 服务器用户名

  14. * @param pwd 服务器密码

  15. * @param port 端口

  16. * @param privateKeyPath 可为空

  17. * @param passphrase 可为空

  18. * @param sourcePath 本地文件路径

  19. * @param destinationPath 上传路径

  20. */

  21. public static void downLoadFile(String ip,String user,String pwd,String port,String privateKeyPath,String passphrase,String sourcePath,String destinationPath){

  22. if (ip != null && !ip.equals("") && user != null && !user.equals("")

  23. && port != null && !port.equals("") && sourcePath != null

  24. && !sourcePath.equals("") && destinationPath != null

  25. && !destinationPath.equals("")) {

  26.  
  27. if (privateKeyPath != null && !privateKeyPath.equals("")) {

  28. sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath,

  29. passphrase, sourcePath, destinationPath);

  30. } else if (pwd != null && !pwd.equals("")) {

  31. sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath,

  32. destinationPath);

  33. } else {

  34. Console console = System.console();

  35. System.out.print("Enter password:");

  36. char[] readPassword = console.readPassword();

  37. sshSftp(ip, user, new String(readPassword),

  38. Integer.parseInt(port), sourcePath, destinationPath);

  39. }

  40. } else {

  41. System.out.println("请先设置配置文件");

  42. }

  43. }

  44. /**

  45. *

  46. * @param properties

  47. */

  48. public static void login(Properties properties) {

  49. String ip = properties.getProperty("ip");

  50. String user = properties.getProperty("user");

  51. String pwd = properties.getProperty("pwd");

  52. String port = properties.getProperty("port");

  53. String privateKeyPath = properties.getProperty("privateKeyPath");

  54. String passphrase = properties.getProperty("passphrase");

  55. String sourcePath = properties.getProperty("sourcePath");

  56. String destinationPath = properties.getProperty("destinationPath");

  57.  
  58. if (ip != null && !ip.equals("") && user != null && !user.equals("")

  59. && port != null && !port.equals("") && sourcePath != null

  60. && !sourcePath.equals("") && destinationPath != null

  61. && !destinationPath.equals("")) {

  62.  
  63. if (privateKeyPath != null && !privateKeyPath.equals("")) {

  64. sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath,

  65. passphrase, sourcePath, destinationPath);

  66. } else if (pwd != null && !pwd.equals("")) {

  67. sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath,

  68. destinationPath);

  69. } else {

  70. Console console = System.console();

  71. System.out.print("Enter password:");

  72. char[] readPassword = console.readPassword();

  73. sshSftp(ip, user, new String(readPassword),

  74. Integer.parseInt(port), sourcePath, destinationPath);

  75. }

  76. } else {

  77. System.out.println("请先设置配置文件");

  78. }

  79. }

  80.  
  81. /**

  82. * 密码方式登录

  83. *

  84. * @param ip

  85. * @param user

  86. * @param psw

  87. * @param port

  88. * @param sPath

  89. * @param dPath

  90. */

  91. public static void sshSftp(String ip, String user, String psw, int port,

  92. String sPath, String dPath) {

  93. System.out.println("password login");

  94. Session session = null;

  95.  
  96. JSch jsch = new JSch();

  97. try {

  98. if (port <= 0) {

  99. // 连接服务器,采用默认端口

  100. session = jsch.getSession(user, ip);

  101. } else {

  102. // 采用指定的端口连接服务器

  103. session = jsch.getSession(user, ip, port);

  104. }

  105.  
  106. // 如果服务器连接不上,则抛出异常

  107. if (session == null) {

  108. throw new Exception("session is null");

  109. }

  110.  
  111. // 设置登陆主机的密码

  112. session.setPassword(psw);// 设置密码

  113. // 设置第一次登陆的时候提示,可选值:(ask | yes | no)

  114. session.setConfig("StrictHostKeyChecking", "no");

  115. // 设置登陆超时时间

  116. session.connect(300000);

  117. UpLoadFile.upLoadFile(session, sPath, dPath);

  118. //DownLoadFile.downLoadFile(session, sPath, dPath);

  119. } catch (Exception e) {

  120. e.printStackTrace();

  121. }

  122.  
  123. System.out.println("success");

  124. }

  125.  
  126. /**

  127. * 密匙方式登录

  128. *

  129. * @param ip

  130. * @param user

  131. * @param port

  132. * @param privateKey

  133. * @param passphrase

  134. * @param sPath

  135. * @param dPath

  136. */

  137. public static void sshSftp2(String ip, String user, int port,

  138. String privateKey, String passphrase, String sPath, String dPath) {

  139. System.out.println("privateKey login");

  140. Session session = null;

  141. JSch jsch = new JSch();

  142. try {

  143. // 设置密钥和密码

  144. // 支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了

  145. if (privateKey != null && !"".equals(privateKey)) {

  146. if (passphrase != null && "".equals(passphrase)) {

  147. // 设置带口令的密钥

  148. jsch.addIdentity(privateKey, passphrase);

  149. } else {

  150. // 设置不带口令的密钥

  151. jsch.addIdentity(privateKey);

  152. }

  153. }

  154. if (port <= 0) {

  155. // 连接服务器,采用默认端口

  156. session = jsch.getSession(user, ip);

  157. } else {

  158. // 采用指定的端口连接服务器

  159. session = jsch.getSession(user, ip, port);

  160. }

  161. // 如果服务器连接不上,则抛出异常

  162. if (session == null) {

  163. throw new Exception("session is null");

  164. }

  165. // 设置第一次登陆的时候提示,可选值:(ask | yes | no)

  166. session.setConfig("StrictHostKeyChecking", "no");

  167. // 设置登陆超时时间

  168. session.connect(300000);

  169. UpLoadFile.upLoadFile(session, sPath, dPath);

  170. System.out.println("success");

  171. } catch (Exception e) {

  172. e.printStackTrace();

  173. }

  174. }

  175.  
  176. }

三:上传主类。

 
  1. package com.cloudpower.util;

  2.  
  3. import java.io.File;

  4. import java.io.FileInputStream;

  5. import java.io.IOException;

  6. import java.io.InputStream;

  7. import java.io.OutputStream;

  8. import java.util.Scanner;

  9.  
  10. import com.jcraft.jsch.Channel;

  11. import com.jcraft.jsch.ChannelSftp;

  12. import com.jcraft.jsch.Session;

  13. import com.jcraft.jsch.SftpException;

  14. public class UpLoadFile {

  15. public static void upLoadFile(Session session, String sPath, String dPath) {

  16.  
  17. Channel channel = null;

  18. try {

  19. channel = (Channel) session.openChannel("sftp");

  20. channel.connect(10000000);

  21. ChannelSftp sftp = (ChannelSftp) channel;

  22. try {

  23. //上传

  24. sftp.cd(dPath);

  25. Scanner scanner = new Scanner(System.in);

  26. System.out.println(dPath + ":此目录已存在,文件可能会被覆盖!是否继续y/n?");

  27. String next = scanner.next();

  28. if (!next.toLowerCase().equals("y")) {

  29. return;

  30. }

  31.  
  32. } catch (SftpException e) {

  33.  
  34. sftp.mkdir(dPath);

  35. sftp.cd(dPath);

  36.  
  37. }

  38. File file = new File(sPath);

  39. copyFile(sftp, file, sftp.pwd());

  40. } catch (Exception e) {

  41. e.printStackTrace();

  42. } finally {

  43. session.disconnect();

  44. channel.disconnect();

  45. }

  46. }

  47.  
  48. public static void copyFile(ChannelSftp sftp, File file, String pwd) {

  49.  
  50. if (file.isDirectory()) {

  51. File[] list = file.listFiles();

  52. try {

  53. try {

  54. String fileName = file.getName();

  55. sftp.cd(pwd);

  56. System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName);

  57. sftp.mkdir(fileName);

  58. System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);

  59. } catch (Exception e) {

  60. // TODO: handle exception

  61. }

  62. pwd = pwd + "/" + file.getName();

  63. try {

  64.  
  65. sftp.cd(file.getName());

  66. } catch (SftpException e) {

  67. // TODO: handle exception

  68. e.printStackTrace();

  69. }

  70. } catch (Exception e) {

  71. // TODO Auto-generated catch block

  72. e.printStackTrace();

  73. }

  74. for (int i = 0; i < list.length; i++) {

  75. copyFile(sftp, list[i], pwd);

  76. }

  77. } else {

  78.  
  79. try {

  80. sftp.cd(pwd);

  81.  
  82. } catch (SftpException e1) {

  83. // TODO Auto-generated catch block

  84. e1.printStackTrace();

  85. }

  86. System.out.println("正在复制文件:" + file.getAbsolutePath());

  87. InputStream instream = null;

  88. OutputStream outstream = null;

  89. try {

  90. outstream = sftp.put(file.getName());

  91. instream = new FileInputStream(file);

  92.  
  93. byte b[] = new byte[1024];

  94. int n;

  95. try {

  96. while ((n = instream.read(b)) != -1) {

  97. outstream.write(b, 0, n);

  98. }

  99. } catch (IOException e) {

  100. // TODO Auto-generated catch block

  101. e.printStackTrace();

  102. }

  103.  
  104. } catch (SftpException e) {

  105. // TODO Auto-generated catch block

  106. e.printStackTrace();

  107. } catch (IOException e) {

  108. // TODO Auto-generated catch block

  109. e.printStackTrace();

  110. } finally {

  111. try {

  112. outstream.flush();

  113. outstream.close();

  114. instream.close();

  115.  
  116. } catch (Exception e2) {

  117. // TODO: handle exception

  118. e2.printStackTrace();

  119. }

  120. }

  121. }

  122. }

  123. }

四:加载配置文件类

 
  1. package com.util;

  2.  
  3. import java.io.File;

  4. import java.io.FileInputStream;

  5. import java.io.IOException;

  6. import java.io.InputStream;

  7. import java.util.Properties;

  8.  
  9. public class LoadProperties {

  10. public static Properties getProperties() {

  11.  
  12. File file = new File(Class.class.getClass().getResource("/").getPath()

  13. + "properties.properties");

  14.  
  15. InputStream inputStream = null;

  16.  
  17. try {

  18. inputStream = new FileInputStream(file);

  19. } catch (IOException e) {

  20. // TODO Auto-generated catch block

  21. e.printStackTrace();

  22. }

  23.  
  24. Properties properties = new Properties();

  25. try {

  26. properties.load(inputStream);

  27. } catch (IOException e) {

  28. // TODO Auto-generated catch block

  29. e.printStackTrace();

  30. }

  31.  
  32. return properties;

  33.  
  34. }

  35. }


楼主亲测,复制即可用。

需要jcraft.jar包

http://maven.outofmemory.cn/com.jcraft/jsch/0.1.51/

下载即可

猜你喜欢

转载自blog.csdn.net/qq_36350477/article/details/85321692