FTPUtils.java 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package io.renren.common.utils;
  2. import com.jcraft.jsch.*;
  3. import org.apache.commons.net.ftp.FTPClient;
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.util.Properties;
  9. import java.util.Vector;
  10. public class FTPUtils {
  11. private static String host;
  12. private static String username;
  13. private static String password;
  14. private static String basePath;
  15. private static int port;
  16. private static ChannelSftp sftp;
  17. private static Channel channel;
  18. private static boolean key_needed;
  19. private static String key_location;
  20. public FTPUtils(String host,String username,String password,String basePath,int port,boolean key_needed,String key_location){
  21. FTPUtils.host=host;
  22. FTPUtils.username=username;
  23. FTPUtils.password=password;
  24. FTPUtils.basePath=basePath;
  25. FTPUtils.port=port;
  26. FTPUtils.key_needed=key_needed;
  27. FTPUtils.key_location=key_location;
  28. initFTPUtil();
  29. }
  30. public void initFTPUtil(){
  31. FTPClient ftp=new FTPClient();
  32. try {
  33. JSch jsch=new JSch();
  34. System.out.println("是否需要秘钥"+key_needed);
  35. if(key_needed){
  36. jsch.addIdentity(key_location);
  37. }
  38. //获取sshSession 账号-ip-端口
  39. Session sshSession=jsch.getSession(username,host,port);
  40. //添加密码
  41. sshSession.setPassword(password);
  42. Properties sshConfig=new Properties();
  43. //严格主机密钥检查
  44. sshConfig.put("StrictHostKeyChecking","no");
  45. sshSession.setConfig(sshConfig);
  46. //开启sshSession连接
  47. sshSession.connect();
  48. //获取sftp通道
  49. channel=sshSession.openChannel("sftp");
  50. channel.connect();
  51. sftp=(ChannelSftp) channel;
  52. ftp.enterLocalPassiveMode();
  53. } catch (JSchException e) {
  54. e.printStackTrace();
  55. }
  56. }
  57. /**
  58. * Description: 在服务器创建文件夹
  59. * @param filePath 要创建的文件夹名,创建位置在basePath下
  60. * @return 成功返回true,否则false
  61. */
  62. public static boolean mkdir(String filePath){
  63. boolean result=false;
  64. try {
  65. sftp.cd("/");
  66. sftp.cd(basePath);
  67. sftp.mkdir(filePath);
  68. return true;
  69. } catch (SftpException e) {
  70. e.printStackTrace();
  71. }
  72. return result;
  73. }
  74. /**
  75. * Description: 向FTP服务器上传文件
  76. * @param filePath FTP服务器文件存放路径。文件的路径为basePath+filePath
  77. * @param filename 上传到FTP服务器上的文件名
  78. * @param input 输入流
  79. * @return 成功返回true,否则false
  80. */
  81. public static boolean uploadFile(String filePath,String filename, InputStream input){
  82. boolean result=false;
  83. try {
  84. sftp.cd("/");
  85. sftp.cd(basePath);
  86. sftp.cd(filePath);
  87. sftp.put(input,filename);
  88. return true;
  89. } catch (SftpException e) {
  90. e.printStackTrace();
  91. }
  92. return result;
  93. }
  94. /**
  95. * Description: 从FTP服务器下载文件
  96. * @param filePath FTP服务器文件存放路径。文件的路径为basePath+filePath
  97. * @return 成功返回true,否则false
  98. */
  99. public static InputStream downloadFile(String filePath){
  100. try {
  101. InputStream inputStream=sftp.get(filePath);
  102. return inputStream;
  103. } catch (SftpException e) {
  104. e.printStackTrace();
  105. }
  106. return null;
  107. }
  108. /**
  109. * Description: 判断目录是否存在
  110. * @param filePath
  111. * @return
  112. */
  113. public static boolean isDirExist(String filePath){
  114. boolean isDirExistFlag=false;
  115. try {
  116. SftpATTRS sftpATTRS=sftp.lstat(basePath+"/"+filePath);
  117. isDirExistFlag=true;
  118. return sftpATTRS.isDir();
  119. } catch (Exception e) {
  120. if (e.getMessage().toLowerCase().equals("no such file")) {
  121. isDirExistFlag = false;
  122. }
  123. }
  124. return isDirExistFlag;
  125. }
  126. /**
  127. * Description: 执行命令
  128. * @param cmd 要执行的命令
  129. * @return 成功返回true,否则false
  130. */
  131. public static String execCmd(String cmd) throws JSchException {
  132. JSch jSch = new JSch();
  133. System.out.println("是否需要秘钥"+key_needed);
  134. if(key_needed){
  135. jSch.addIdentity(key_location);
  136. }
  137. Session session = null;
  138. ChannelExec channelExec = null;
  139. BufferedReader inputStreamReader = null;
  140. BufferedReader errInputStreamReader = null;
  141. StringBuilder runLog = new StringBuilder("");
  142. StringBuilder errLog = new StringBuilder("");
  143. try {
  144. // 1. 获取 ssh session
  145. session = jSch.getSession(username, host, port);
  146. session.setPassword(password);
  147. session.setTimeout(60 * 60 * 1000);
  148. session.setConfig("StrictHostKeyChecking", "no");
  149. session.connect(); // 获取到 ssh session
  150. // 2. 通过 exec 方式执行 shell 命令
  151. channelExec = (ChannelExec) session.openChannel("exec");
  152. channelExec.setCommand(cmd);
  153. channelExec.connect(); // 执行命令
  154. // 3. 获取标准输入流
  155. inputStreamReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
  156. // 4. 获取标准错误输入流
  157. errInputStreamReader = new BufferedReader(new InputStreamReader(channelExec.getErrStream()));
  158. // 5. 记录命令执行 log
  159. String line = null;
  160. while ((line = inputStreamReader.readLine()) != null) {
  161. runLog.append(line).append("\n");
  162. }
  163. // 6. 记录命令执行错误 log
  164. String errLine = null;
  165. while ((errLine = errInputStreamReader.readLine()) != null) {
  166. errLog.append(errLine).append("\n");
  167. }
  168. // 7. 输出 shell 命令执行日志
  169. System.out.println("exitStatus=" + channelExec.getExitStatus() + ", openChannel.isClosed="
  170. + channelExec.isClosed());
  171. System.out.println("命令执行完成,执行日志如下:");
  172. System.out.println(runLog.toString());
  173. System.out.println("命令执行完成,执行错误日志如下:");
  174. System.out.println(errLog.toString());
  175. } catch (Exception e) {
  176. e.printStackTrace();
  177. } finally {
  178. try {
  179. if (inputStreamReader != null) {
  180. inputStreamReader.close();
  181. }
  182. if (errInputStreamReader != null) {
  183. errInputStreamReader.close();
  184. }
  185. if (channelExec != null) {
  186. channelExec.disconnect();
  187. }
  188. if (session != null) {
  189. session.disconnect();
  190. }
  191. } catch (IOException e) {
  192. e.printStackTrace();
  193. }
  194. }
  195. return runLog.append(errLog).toString();
  196. }
  197. /**
  198. * Description: 显示目标地址下的文件 地址为basePath+filePath
  199. * @param filePath
  200. * @return
  201. */
  202. public static Vector<ChannelSftp.LsEntry> showFiles(String filePath){
  203. Vector vector=new Vector();
  204. try {
  205. vector=sftp.ls(basePath+"/"+filePath);
  206. } catch (SftpException e) {
  207. e.printStackTrace();
  208. }
  209. return vector;
  210. }
  211. }