JAvaコードsshベースlinuxサーバファイル間アップロードを実現
7260 ワード
プロジェクト機能のため、linuxからlinuxサーバへのファイルのアップロードを実現する必要があります.次のコードは、sshプロトコルに基づいて、新しいアップロードが利用可能である別のブログをオンラインで参照しています.ローカルファイルは接尾辞なしで保存されているので、接尾辞付きの再呼び出しアップロードをローカルで一時的にコピーします(ファイルに接尾辞があれば直接アップロードできます).
package com.***.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.io.FilenameUtils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.strongit.form.vo.FormProperty;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
* SFTP
* @author htt
*
*/
public class SFTPUtil {
private static Log log = LogFactory.getLog(SFTPUtil.class);
/**
* sftp
* @param host ip
* @param port sftp ,null
* @param user
* @param password
* @return
* @throws JSchException
*/
public static Session connect(String host, Integer port, String user, String password) throws JSchException{
Session session = null;
try {
JSch jsch = new JSch();
if(port != null){
session = jsch.getSession(user, host, port.intValue());
}else{
session = jsch.getSession(user, host);
}
session.setPassword(password);
// , :(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
//30
session.connect(30000);
} catch (JSchException e) {
e.printStackTrace();
System.out.println("SFTPUitl ");
throw e;
}
return session;
}
/**
* sftp ( )
* @param directory
* @param uploadFile
* @param sftp
* @throws Exception
*/
public static void upload(String directory, String uploadFile, ChannelSftp sftp) throws Exception{
System.out.println("sftp upload file [directory] : "+directory);
System.out.println("sftp upload file [uploadFile] : "+ uploadFile);
File file = new File(uploadFile);
if(file.exists()){
// , ChannelSftp linux ,
try {
Vector content = sftp.ls(directory);
if(content == null){
sftp.mkdir(directory);
}
} catch (SftpException e) {
sftp.mkdir(directory);
}
//
sftp.cd(directory);
if(file.isFile()){
InputStream ins = new FileInputStream(file);
//
sftp.put(ins, new String(file.getName().getBytes(),"UTF-8"));
//sftp.setFilenameEncoding("UTF-8");
}else{
File[] files = file.listFiles();
for (File file2 : files) {
String dir = file2.getAbsolutePath();
if(file2.isDirectory()){
String str = dir.substring(dir.lastIndexOf(file2.separator));
directory = FilenameUtils.normalize(directory + str);
}
upload(directory,dir,sftp);
}
}
}
}
/**
* sftp ( )
* @param directory
* @param srcFile
* @param saveFile
* @param sftp ChannelSftp
* @throws UnsupportedEncodingException
*/
public static void download(String directory,String srcFile, String saveFile, ChannelSftp sftp) throws UnsupportedEncodingException {
Vector conts = null;
try{
conts = sftp.ls(srcFile);
} catch (SftpException e) {
e.printStackTrace();
log.debug("ChannelSftp sftp ",e);
}
File file = new File(saveFile);
if(!file.exists()) file.mkdir();
//
if(srcFile.indexOf(".") > -1){
try {
sftp.get(srcFile, saveFile);
} catch (SftpException e) {
e.printStackTrace();
log.debug("ChannelSftp sftp ",e);
}
}else{
// ( )
for (Iterator iterator = conts.iterator(); iterator.hasNext();) {
LsEntry obj = (LsEntry) iterator.next();
String filename = new String(obj.getFilename().getBytes(),"UTF-8");
if(!(filename.indexOf(".") > -1)){
directory = FilenameUtils.normalize(directory + System.getProperty("file.separator") + filename);
srcFile = directory;
saveFile = FilenameUtils.normalize(saveFile + System.getProperty("file.separator") + filename);
}else{
// ".."
String[] arrs = filename.split("\\.");
if((arrs.length > 0) && (arrs[0].length() > 0)){
srcFile = FilenameUtils.normalize(directory + System.getProperty("file.separator") + filename);
}else{
continue;
}
}
download(directory, srcFile, saveFile, sftp);
}
}
}
protected final Log logger = LogFactory.getLog(this.getClass());
public static void main(String args[]){
String host = "192.168.1.168";
int port = 22;
String username = "root";
String password = "password";
String destDir = "/app";
ChannelSftp sftp = null;
Session session = null;
try {
session = SFTPUtil.connect(host, port, username, password);
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
System.out.println(" +++++:" + wa.getAttachName());
File local_src = new File("D:\\attachments\\402848e6641fea5e01641fee65690002");
System.out.println("local_src+++++:" + local_src.getAbsolutePath());
String newfile_name = 1234 - .docx;
//windows
//File local_dest = new File(StringUtils.substringBeforeLast(local_src.getAbsolutePath(),"\\") +"\
amed\\"+newfile_name);
//linux
File local_dest = new File(StringUtils.substringBeforeLast(local_src.getAbsolutePath(), "/") + "/named/" + newfile_name);
System.out.println("local_dest+++++:" + local_dest.getAbsolutePath());
//
FileUtil.copy(local_src, local_dest);
System.out.println("copy+++++ok");
// linux
SFTPUtil.upload(destDir, local_dest.getAbsolutePath(), sftp);
System.out.println("upload+++++ok");
} catch (Exception e) {
e.printStackTrace();
//logger.debug(e);
//return UtilMisc.toMap("flag","failure","msg"," ");
}finally{
if(sftp != null)sftp.disconnect();
if(session != null)session.disconnect();
}
}
}
public static boolean copy(File src, File dest) {
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(src));
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(dest));
byte[] bts = new byte[1024];
int len = -1;
while ((len = bufferedInputStream.read(bts)) != -1) {
bufferedOutputStream.write(bts, 0, len);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (bufferedInputStream != null) {
try {
bufferedInputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.close();
} catch (Exception e3) {
e3.printStackTrace();
}
}
}
}