使用说明:用于linux SCP
public class UploadFileUtil {
private final Logger logger = LoggerFactory.getLogger(getClass()) ;
// scp ip地址
private String address = "" ;
// scp 端口号
private int port = 0 ;
// scp 用户名
private String username = "" ;
// scp 密码
private String password = "" ;
// scp文件根目录
private String path = "" ;
//0755是指权限编号
private String mode = "" ;
// 文件路径
private String subPath = "" ;
/**
* 方法功能说明:通过scp上传任何文件
* @param fileName 文件全路径
* @return 返回"200"则上传成功,"500" 则上传失败出现异常 ,"506"则登陆远程服务器失败
*/
public String upLoadFile(String fileName){
if (logger.isDebugEnabled()) {
logger.debug("==============开始上传====" + fileName + "==============");
}
Connection con = null ;
Session session = null ;
InputStream stdout = null ;
BufferedReader br = null ;
SCPOutputStream out = null ;
FileInputStream in = null ;
try {
if (logger.isDebugEnabled()) {
logger.debug("加入SCP实现远程传输文件");
}
// 加入SCP实现远程传输文件
con = new Connection(address, port);
if (logger.isDebugEnabled()) {
logger.debug("开始连接");
}
// 连接
con.connect();
if (logger.isDebugEnabled()) {
logger.debug("登陆远程服务器" + username + "," + password);
}
// 登陆远程服务器的用户名密码
boolean isAuthed = con.authenticateWithPassword(username, password);
// 登陆失败
if (!isAuthed) {
if (logger.isDebugEnabled()) {
logger.debug("登陆远程服务器失败");
}
return "506";
}
if (logger.isDebugEnabled()) {
logger.debug("建立scp客户端");
}
// 建立SCP客户端
SCPClient scpClient = con.createSCPClient();
if (logger.isDebugEnabled()) {
logger.debug("开始上传文件到服务器");
}
// 权限编号
//scpClient.put(fileName, path+subPath, mode); 210 jar包写法 且没有以下部分
File f = new File(fileName) ;
session = con.openSession();
//创建远程目录
String remotePath = path+"/"+subPath;
session.execCommand("mkdir -p "+remotePath);
//显示执行命令后的信息
stdout = new StreamGobbler(session.getStdout());
br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null) {
logger.info("远程服务器返回信息:空");
break;
}
logger.info("远程服务器返回信息:" + line);
}
//获得推出状态
logger.info("ExitCode: " + session.getExitStatus());
// 上传文件到远程地址
out = scpClient.put(f.getName(), f.length(), remotePath, mode) ;
in = new FileInputStream(f) ;
IOUtils.copy(in, out) ;
if (logger.isDebugEnabled()) {
logger.debug("关闭连接");
}
if (logger.isDebugEnabled()) {
logger.debug("上传完成");
}
return "200";
} catch (Exception e) {
logger.error("上传失败", e.getMessage(), e);
return "500";
}finally{
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(stdout!=null){
try {
stdout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(in!=null){
try {
in.close() ;
} catch (IOException e) {
logger.error("",e);
}
}
if(out!=null){
try {
out.close() ;
} catch (IOException e) {
logger.error("",e);
}
}
if(session!=null){
session.close();
}
if(con!=null){
con.close();
}
}
}
}