From edcff8ef21cb1c03f3009a5d76df545388d386d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=E5=98=89=E9=98=B3?= Date: Thu, 10 May 2018 21:39:55 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E9=80=9A=E8=BF=87java?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=E5=91=BD=E4=BB=A4=E8=A1=8C=E5=8E=8B=E7=BC=A9?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 8 + .../spring/controller/DownLoadController.java | 67 +++++++- .../spring/controller/UpLoadController.java | 43 ----- .../properties/RemoteExecuteProperties.java | 19 +++ .../fjy/spring/untils/FtpOperationUtil.java | 4 +- .../untils/RemoteExecuteCommandUtil.java | 161 ++++++++++++++++++ src/main/resources/application-dev.yml | 5 + .../untils/RemoteExecuteCommandUtilTest.java | 67 ++++++++ 8 files changed, 325 insertions(+), 49 deletions(-) create mode 100644 src/main/java/com/fjy/spring/properties/RemoteExecuteProperties.java create mode 100644 src/main/java/com/fjy/spring/untils/RemoteExecuteCommandUtil.java create mode 100644 src/test/java/com/fjy/spring/untils/RemoteExecuteCommandUtilTest.java diff --git a/pom.xml b/pom.xml index 71c93fe..4ab20b5 100644 --- a/pom.xml +++ b/pom.xml @@ -99,6 +99,14 @@ 1.3.3 + + + org.apache.commons + commons-lang3 + 3.7 + + + diff --git a/src/main/java/com/fjy/spring/controller/DownLoadController.java b/src/main/java/com/fjy/spring/controller/DownLoadController.java index 631e2a6..96d6857 100644 --- a/src/main/java/com/fjy/spring/controller/DownLoadController.java +++ b/src/main/java/com/fjy/spring/controller/DownLoadController.java @@ -5,12 +5,14 @@ import com.fjy.spring.domain.TbLog; import com.fjy.spring.domain.TbUser; import com.fjy.spring.enums.ResultEnum; import com.fjy.spring.exception.UserException; +import com.fjy.spring.properties.RemoteExecuteProperties; import com.fjy.spring.properties.ServerProperties; import com.fjy.spring.service.FileService; import com.fjy.spring.service.LogService; import com.fjy.spring.untils.FtpOperationUtil; import com.fjy.spring.untils.FtpUtils; import com.fjy.spring.untils.LogUtil; +import com.fjy.spring.untils.RemoteExecuteCommandUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; @@ -35,6 +37,7 @@ import java.util.zip.ZipOutputStream; import static com.fjy.spring.constant.GlobalConstant.USER_SESSION_KEY; @Controller +@Slf4j public class DownLoadController { /** * 服务器配置信息 @@ -42,6 +45,9 @@ public class DownLoadController { @Autowired private ServerProperties serverProperties; + @Autowired + private RemoteExecuteProperties remoteExecuteProperties; + @Autowired private FileService fileService; @@ -175,9 +181,9 @@ public class DownLoadController { System.out.println(str); } String path = "/upload/" + tbFile.getCourseName() + "/" + tbFile.getWorkFolder() + "/"; - System.out.println("【path】"+path); - InputStream inputStream = ftpUtil.downFile(path,tbFile.getColfilename()); - System.out.println("【available】"+inputStream.available()); + System.out.println("【path】" + path); + InputStream inputStream = ftpUtil.downFile(path, tbFile.getColfilename()); + System.out.println("【available】" + inputStream.available()); bis = new BufferedInputStream(inputStream); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; @@ -220,7 +226,6 @@ public class DownLoadController { * @param folder * @param response */ - @GetMapping("/home/admin/download/downloadzip") public void batDownload(@RequestParam(value = "courseName") String courseName, @RequestParam(value = "Folder") String folder, HttpServletResponse response) { //获取文件夹名称 @@ -328,6 +333,60 @@ public class DownLoadController { } } + @GetMapping("/home/admin/download/downloadzip") + public void batFTPDownloadZip(@RequestParam(value = "courseName") String courseName, + @RequestParam(value = "Folder") String folder, HttpServletResponse response) throws IOException { + //获取文件夹名称 + String paths = "/upload/" + courseName + "/" + folder; + String zipPath = "/zip/"; + List pathList; + pathList = getFileString(paths); + //需要压缩的文件--包括文件地址和文件名 + String[] path = pathList.toArray(new String[0]); + // 要生成的压缩文件地址和文件名称 + String zipFileName = courseName + folder + ".zip"; + String desPath = zipPath + "/" + zipFileName; + //System.out.println("打包文件存储地址:"+desPath); + + //远程登录SSH + RemoteExecuteCommandUtil rec = new RemoteExecuteCommandUtil( + remoteExecuteProperties.getIp(), + remoteExecuteProperties.getUser(), + remoteExecuteProperties.getPassword()); + rec.login(); + //登录FTP + FtpOperationUtil ftpOperationUtil = new FtpOperationUtil(); + ftpOperationUtil.connectServer(); + + if (!ftpOperationUtil.existDirectory(zipPath)) { + ftpOperationUtil.createDirectory(zipPath); + } + + String desZipPath = remoteExecuteProperties.getPath() + "zip/"; + + String cmd = "zip -r " + desZipPath + zipFileName + " " + remoteExecuteProperties.getPath() + "upload/" + courseName + "/" + folder; + System.out.println("【cmd】" + cmd); + if (rec.executeSuccess(cmd).equals("")) { + log.error("【cmd创建压缩文件失败】" + cmd); + } + + response.setContentType("application/x-msdownload;"); + response.setHeader("Content-disposition", "attachment; filename=" + new String(zipFileName.getBytes("utf-8"), "ISO8859-1")); + + InputStream inputStream = ftpOperationUtil.downFile("/zip/",zipFileName); + System.out.println("【available】" + inputStream.available()); + //将打包好的文件输出到客户端 + BufferedInputStream bis = new BufferedInputStream(inputStream); + BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); + byte[] buff = new byte[2048]; + int bytesRead; + while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { + bos.write(buff, 0, bytesRead); + } + // 记录下载日志 + addVisitLog("下载文件" + desZipPath + zipFileName); + } + /** * 获取目录下所有文件的路径 * diff --git a/src/main/java/com/fjy/spring/controller/UpLoadController.java b/src/main/java/com/fjy/spring/controller/UpLoadController.java index eda9dd3..a62ef9b 100644 --- a/src/main/java/com/fjy/spring/controller/UpLoadController.java +++ b/src/main/java/com/fjy/spring/controller/UpLoadController.java @@ -177,14 +177,6 @@ public class UpLoadController { uploadUrl = serverProperties.getFilePath() + "upload/"; } - - File dir = new File(uploadUrl); - if (!dir.exists()) { - dir.mkdirs(); - } - - List fileList = new ArrayList(); - for (MultipartFile file : files.values()) { Homework homework = new Homework(); @@ -213,31 +205,6 @@ public class UpLoadController { File targetFile = new File(pathname); - /*if (targetFile.exists()) { - String bakpathname; - if (rename) { - bakpathname = uploadUrl + "bak/" + user.getColstudentno() + user.getColrealname() + suffix; - } else { - bakpathname = uploadUrl + "bak/" + filename; - } - log.info("源文件路径:" + pathname); - TbFile file1 = fileService.findByFilepath(pathname); - file1.setColfilepath(bakpathname + "." + dateNowStr2 + ".bak"); - file1.setColfilename(file1.getColfilename() + "." + dateNowStr2 + ".bak"); - if (fileService.addFile(file1)) { - log.info("重命名文件数据库更新成功"); - } else { - log.error("重命名文件数据库更新失败"); - } - File mvfile = new File(bakpathname + "." + dateNowStr2 + ".bak"); - try { - FileUtils.moveFile(targetFile, mvfile); - log.info("源文件:" + targetFile.getName() + "已重命名为:" + mvfile.getName()); - } catch (IOException e) { - e.printStackTrace(); - } - }*/ - log.info("文件上传到: " + uploadUrl + filename); log.info("文件大小: " + FormatFileSizeUtil.GetFileSize(file.getSize())); log.info("文件名: " + filename); @@ -309,16 +276,6 @@ public class UpLoadController { } catch (IOException e) { e.printStackTrace(); } - - try { - file.transferTo(targetFile); - fileList.add( - request.getScheme() + "://" + request.getServerName() + ":" - + serverProperties.getPortNum() + request.getContextPath() + "/upload/" - + file.getOriginalFilename()); - } catch (Exception e) { - e.printStackTrace(); - } } } } diff --git a/src/main/java/com/fjy/spring/properties/RemoteExecuteProperties.java b/src/main/java/com/fjy/spring/properties/RemoteExecuteProperties.java new file mode 100644 index 0000000..8ce6f9c --- /dev/null +++ b/src/main/java/com/fjy/spring/properties/RemoteExecuteProperties.java @@ -0,0 +1,19 @@ +package com.fjy.spring.properties; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * @author F嘉阳 + * @date 2018-05-10 12:34 + */ +@Data +@ConfigurationProperties(prefix = "remoteproperties") +@Component +public class RemoteExecuteProperties { + private String ip; + private String user; + private String password; + private String path; +} diff --git a/src/main/java/com/fjy/spring/untils/FtpOperationUtil.java b/src/main/java/com/fjy/spring/untils/FtpOperationUtil.java index 52f951c..8f3b1d7 100644 --- a/src/main/java/com/fjy/spring/untils/FtpOperationUtil.java +++ b/src/main/java/com/fjy/spring/untils/FtpOperationUtil.java @@ -534,12 +534,12 @@ public class FtpOperationUtil { return ftpClient.retrieveFileStream(sourceFileName); } - public InputStream downFile(String path,String sourceFileName) throws IOException { + public InputStream downFile(String path, String sourceFileName) throws IOException { sourceFileName = new String(sourceFileName.getBytes("UTF-8"), "iso-8859-1"); path = new String(path.getBytes("UTF-8"), "iso-8859-1"); if (path != null && path.length() != 0) { boolean flagChange = ftpClient.changeWorkingDirectory(path); - System.out.println("【目录切换】" + flagChange); + System.out.println("【目录切换】" + path + flagChange); } return ftpClient.retrieveFileStream(sourceFileName); } diff --git a/src/main/java/com/fjy/spring/untils/RemoteExecuteCommandUtil.java b/src/main/java/com/fjy/spring/untils/RemoteExecuteCommandUtil.java new file mode 100644 index 0000000..43b6eb7 --- /dev/null +++ b/src/main/java/com/fjy/spring/untils/RemoteExecuteCommandUtil.java @@ -0,0 +1,161 @@ +package com.fjy.spring.untils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import org.apache.commons.lang3.StringUtils; +import ch.ethz.ssh2.Connection; +import ch.ethz.ssh2.Session; +import ch.ethz.ssh2.StreamGobbler; +/** + * @author F嘉阳 + * @date 2018-05-10 12:16 + */ +public class RemoteExecuteCommandUtil { + //字符编码默认是utf-8 + private static String DEFAULTCHART="UTF-8"; + private Connection conn; + private String ip; + private String userName; + private String userPwd; + + public RemoteExecuteCommandUtil(String ip, String userName, String userPwd) { + this.ip = ip; + this.userName = userName; + this.userPwd = userPwd; + } + + + public RemoteExecuteCommandUtil() { + + } + + /** + * 远程登录linux的主机 + * @author Ickes + * @since V0.1 + * @return + * 登录成功返回true,否则返回false + */ + public Boolean login(){ + boolean flg=false; + try { + conn = new Connection(ip); + conn.connect();//连接 + flg=conn.authenticateWithPassword(userName, userPwd);//认证 + } catch (IOException e) { + e.printStackTrace(); + } + return flg; + } + /** + * @author Ickes + * 远程执行shll脚本或者命令 + * @param cmd + * 即将执行的命令 + * @return + * 命令执行完后返回的结果值 + * @since V0.1 + */ + public String execute(String cmd){ + String result=""; + try { + if(login()){ + Session session= conn.openSession();//打开一个会话 + session.execCommand(cmd);//执行命令 + result=processStdout(session.getStdout(),DEFAULTCHART); + //如果为得到标准输出为空,说明脚本执行出错了 + if(StringUtils.isBlank(result)){ + result=processStdout(session.getStderr(),DEFAULTCHART); + } + conn.close(); + session.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + + /** + * @author Ickes + * 远程执行shll脚本或者命令 + * @param cmd + * 即将执行的命令 + * @return + * 命令执行成功后返回的结果值,如果命令执行失败,返回空字符串,不是null + * @since V0.1 + */ + public String executeSuccess(String cmd){ + String result=""; + try { + if(login()){ + Session session= conn.openSession();//打开一个会话 + session.execCommand(cmd);//执行命令 + result=processStdout(session.getStdout(),DEFAULTCHART); + conn.close(); + session.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + return result; + } + + /** + * 解析脚本执行返回的结果集 + * @author Ickes + * @param in 输入流对象 + * @param charset 编码 + * @since V0.1 + * @return + * 以纯文本的格式返回 + */ + private String processStdout(InputStream in, String charset){ + InputStream stdout = new StreamGobbler(in); + StringBuffer buffer = new StringBuffer();; + try { + BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset)); + String line=null; + while((line=br.readLine()) != null){ + buffer.append(line+"\n"); + } + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return buffer.toString(); + } + + public static void setCharset(String charset) { + DEFAULTCHART = charset; + } + public Connection getConn() { + return conn; + } + public void setConn(Connection conn) { + this.conn = conn; + } + public String getIp() { + return ip; + } + public void setIp(String ip) { + this.ip = ip; + } + public String getUserName() { + return userName; + } + public void setUserName(String userName) { + this.userName = userName; + } + public String getUserPwd() { + return userPwd; + } + public void setUserPwd(String userPwd) { + this.userPwd = userPwd; + } +} \ No newline at end of file diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index e702b4a..5d06ed7 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -8,6 +8,11 @@ server: serverproperties: port_num: 8080 filePath: F:\JAVA Workspace\Temp\ +remoteproperties: + ip: 192.168.79.138 + user: root + password: 27894869 + path: /home/ftp/cms/ spring: thymeleaf: prefix: classpath:/templates/ diff --git a/src/test/java/com/fjy/spring/untils/RemoteExecuteCommandUtilTest.java b/src/test/java/com/fjy/spring/untils/RemoteExecuteCommandUtilTest.java new file mode 100644 index 0000000..76f750b --- /dev/null +++ b/src/test/java/com/fjy/spring/untils/RemoteExecuteCommandUtilTest.java @@ -0,0 +1,67 @@ +package com.fjy.spring.untils; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class RemoteExecuteCommandUtilTest { + + RemoteExecuteCommandUtil rec=new RemoteExecuteCommandUtil("192.168.79.138", "root","27894869"); + + @Test + public void login() { + rec.login(); + System.out.println(rec.execute("ifconfig")); + } + + @Test + public void execute() { + + } + + @Test + public void executeZip() { + rec.login(); + System.out.println(rec.execute("zip -r /home/ftp/cms/upload/信息安全时间测试.zip /home/ftp/cms/upload/信息安全")); + } + + @Test + public void executeSuccess() { + } + + @Test + public void setCharset() { + } + + @Test + public void getConn() { + } + + @Test + public void setConn() { + } + + @Test + public void getIp() { + } + + @Test + public void setIp() { + } + + @Test + public void getUserName() { + } + + @Test + public void setUserName() { + } + + @Test + public void getUserPwd() { + } + + @Test + public void setUserPwd() { + } +} \ No newline at end of file