首页 > 代码库 > 远程服务器下载文件到本地服务器

远程服务器下载文件到本地服务器

package mytiny.com.controller;

import org.apache.log4j.Logger;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import mytiny.com.common.CommonFunc;

/**
* @description 将视频从各个服务器上转移到本地的服务器上 ganymed-ssh2-build210.jar
*
* @author 葛浩润      
* @time 2016-11-28
*
*/
public class SCPVideo {
private static Logger logger = Logger.getLogger(SCPVideo.class);
static Connection con = null;

/**
* 下载到本地
*
* @throws Exception
*/
public static boolean downLoadVideo(String IP, String remotePath, String localPath) throws Exception {

try {
// 建立SCP客户端
SCPClient scpClient = connectRemote(IP);
if (scpClient != null) {
// 服务器端的文件下载到本地的目录下
scpClient.get(remotePath, localPath);
return true;
}else{
logger.info("服务器连接失败");
return false;
}

} catch (Exception e) {
logger.info(e);
System.out.println(e);
return false;
} finally {
if (con != null) {
con.close();
}
}

}

/**
* 上传到远程
*
* @throws Exception
*/
public static void upLoadVideo(String IP) throws Exception {
// 建立SCP客户端
SCPClient scpClient = connectRemote(IP);
if (scpClient != null) {
// 文件上传到远程路径下
scpClient.put("/home/ghr/111.docx", "/workspace/5.content/bak/20161123");
}

if (con != null) {
con.close();
}

}

/**
* 连接远程服务器,返回true连接成功,返回false连接失败
*
* @throws Exception
*/
public static SCPClient connectRemote(String IP) throws Exception {
try {
con = new Connection(IP);
con.connect();
// 远程服务器的用户名密码
boolean isAuthed = con.authenticateWithPassword(CommonFunc.getProperties(IP + ".User"), CommonFunc.getProperties(IP + ".Pass"));
if (isAuthed) {
// 建立SCP客户端
SCPClient scpClient = con.createSCPClient();
return scpClient;
} else {
logger.error("连接远程服务器失败!");
System.out.println("连接远程服务器失败!");
return null;
}
} catch (Exception e) {
logger.error("服务器连接失败 IP:"+IP);
return null;
}

}

}

远程服务器下载文件到本地服务器