<dependency> <groupId>ch.ethz.ganymed</groupId> <artifactId>ganymed-ssh2</artifactId> <version>build210</version> </dependency>
- 登录远程服务器
public boolean login(){ //创建远程连接,默认连接端口为22,如果不使用默认,可以使用方法 //new Connection(ip, port)创建对象 Connection conn = new Connection(ip); try { //连接远程服务器 conn.connect(); //使用用户名和密码登录 return conn.authenticateWithPassword(usr, psword); } catch (IOException e) { System.err.printf("用户%s密码%s登录服务器%s失败!", usr, psword, ip); e.printStackTrace(); } return false; }
/** * 上传本地文件到服务器目录下 * @param conn Connection对象 * @param fileName 本地文件 * @param remotePath 服务器目录 */ public void putFile(Connection conn, String fileName, String remotePath){ SCPClient sc = new SCPClient(conn); try { //将本地文件放到远程服务器指定目录下,默认的文件模式为 0600,即 rw, //如要更改模式,可调用方法 put(fileName, remotePath, mode),模式须是4位数字且以0开头 sc.put(fileName, remotePath); } catch (IOException e) { e.printStackTrace(); } }
/** * 下载服务器文件到本地目录 * @param fileName 服务器文件 * @param localPath 本地目录 */ public void copyFile(Connection conn, String fileName,String localPath){ SCPClient sc = new SCPClient(conn); try { sc.get(fileName, localPath); } catch (IOException e) { e.printStackTrace(); } }
/** * 获得远程服务器文件夹下所有文件 * * @param remoteDir * @param localTargetDirectory */ public void getFiles(String remoteDir, String localTargetDirectory) { Connection conn = new Connection(ip, port); Connection conn2 = getConn2(ip, port, username, password); SFTPv3Client sft = null; try { conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (!isAuthenticated) { System.err.println("authentication failed"); } SCPClient client = new SCPClient(conn); sft = new SFTPv3Client(conn2); //获取远程目录下文件列表 Vector<?> v = sft.ls(remoteDir); for (int i = 0; i < v.size(); i++) { SFTPv3DirectoryEntry s = (SFTPv3DirectoryEntry) v.get(i); if (fileType(s.filename)) { client.get(remoteDir + "/" + s.filename, localTargetDirectory); } } } catch (IOException e) { throw new RuntimeException(e); } finally { if (sft != null) { sft.close(); } if (conn != null) { conn.close(); } } }
/** * 在远程LINUX服务器上,在指定目录下,获取文件各个属性 * @param[in] conn Conncetion对象 * @param[in] remotePath 远程主机的指定目录 */ public void getFileProperties(Conncetion conn, String remotePath){ try { SFTPv3Client sft = new SFTPv3Client(conn); Vector<?> v = sft.ls(remotePath); for(int i=0;i<v.size();i++){ SFTPv3DirectoryEntry s = new SFTPv3DirectoryEntry(); s = (SFTPv3DirectoryEntry) v.get(i); //文件名 String filename = s.filename; //文件的大小 Long fileSize = s.attributes.size; } sft.close(); } catch (Exception e1) { e1.printStackTrace(); } }
/** * 在远程LINUX服务器上,在指定目录下,删除指定文件 * @param[in] fileName 文件名 * @param[in] remotePath 远程主机的指定目录 * @return */ public void delFile(String remotePath, String fileName){ try { SFTPv3Client sft = new SFTPv3Client(conn); //获取远程目录下文件列表 Vector<?> v = sft.ls(remotePath); for(int i=0;i<v.size();i++){ SFTPv3DirectoryEntry s = new SFTPv3DirectoryEntry(); s = (SFTPv3DirectoryEntry) v.get(i); //判断列表中文件是否与指定文件名相同 if(s.filename.equals(fileName)){ //rm()方法中,须是文件绝对路径+文件名称 sft.rm(remotePath + s.filename); } sft.close(); } catch (Exception e1) { e1.printStackTrace(); } }
/** * 执行脚本 * @param conn Connection对象 * @param cmds 要在linux上执行的指令 */ public int exec(Connection conn, String cmds){ InputStream stdOut = null; InputStream stdErr = null; int ret = -1; try { //在connection中打开一个新的会话 Session session = conn.openSession(); //在远程服务器上执行linux指令 session.execCommand(cmds); //指令执行结束后的输出 stdOut = new StreamGobbler(session.getStdout()); //指令执行结束后的错误 stdErr = new StreamGobbler(session.getStderr()); //等待指令执行结束 session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); //取得指令执行结束后的状态 ret = session.getExitStatus(); conn.close(); }catch(Exception e){ e.printStackTrace(); } return ret; }
- controller
package com.sun.redis.controller; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.sun.redis.util.FileUtil; import com.sun.redis.util.LinuxLogin; @RestController @RequestMapping("/fileDownCtl") public class FileDownController { @Autowired private FileUtil fileUtil; @Autowired private LinuxLogin linuxLogin; @RequestMapping(value="/getFile",method=RequestMethod.GET) public void getFile(HttpServletResponse response){ String path = "D:/Games/WarCraft/BeeWind软件站说明.txt"; fileUtil.getListFileList(path, response); } @RequestMapping(value="/getLinuxFile",method=RequestMethod.GET) public void getLinuxFile(HttpServletResponse response) throws IOException{ String fileName = "linux.txt"; String path = "/home/hadoop/text/"; linuxLogin.login(); response.reset(); response.setContentType("bin"); response.setContentType("octets/stream"); response.addHeader("Content-Type", "text/html; charset=utf-8"); response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1")); linuxLogin.copyFile(linuxLogin.conn, path+fileName,response.getOutputStream()); } }
- 工具类
package com.sun.redis.util; import java.io.IOException; import java.util.Vector; import javax.servlet.ServletOutputStream; import org.springframework.stereotype.Component; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.SCPClient; import ch.ethz.ssh2.SFTPv3Client; import ch.ethz.ssh2.SFTPv3DirectoryEntry; @Component public class LinuxLogin { public static Connection conn = null; public boolean login(){ //创建远程连接,默认连接端口为22,如果不使用默认,可以使用方法 //new Connection(ip, port)创建对象 conn = new Connection("192.168.159.128"); try { //连接远程服务器 conn.connect(); //使用用户名和密码登录 return conn.authenticateWithPassword("hadoop", "hadoop"); } catch (IOException e) { System.err.printf("用户%s密码%s登录服务器%s失败!", "hadoop", "hadoop", "192.168.159.128"); e.printStackTrace(); } return false; } /** * 复制到JAVA所在服务器 * @param conn * @param fileName * @param localPath */ public void copyFile(Connection conn, String fileName,String localPath){ SCPClient sc = new SCPClient(conn); try { sc.get(fileName, localPath); } catch (IOException e) { e.printStackTrace(); } } /** * 流式输出,用于浏览器下载 * @param conn * @param fileName * @param outputStream */ public void copyFile(Connection conn, String fileName,ServletOutputStream outputStream){ SCPClient sc = new SCPClient(conn); try { sc.get(fileName, outputStream); } catch (IOException e) { e.printStackTrace(); } } /** * 在远程LINUX服务器上,在指定目录下,获取文件各个属性 * @param[in] conn Conncetion对象 * @param[in] remotePath 远程主机的指定目录 */ public void getFileProperties(Connection conn, String remotePath){ try { SFTPv3Client sft = new SFTPv3Client(conn); Vector<?> v = sft.ls(remotePath); for(int i=0;i<v.size();i++){ SFTPv3DirectoryEntry s = new SFTPv3DirectoryEntry(); s = (SFTPv3DirectoryEntry) v.get(i); //文件名 String filename = s.filename; //文件的大小 Long fileSize = s.attributes.size; } sft.close(); } catch (Exception e1) { e1.printStackTrace(); } } public static void main(String args[]){ LinuxLogin log = new LinuxLogin(); System.out.println(log.login()); } }