pom
</dependency>
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
package com.taskschedule.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SFTPException;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
/**
*
* @author baoyou E-mail:[email protected]
* @version 2016年11月2日 下午1:54:43
* desc:
*/
public class Scp {
private static Logger logger = Logger.getLogger(Scp.class);
/**
* 遠端檔案傳輸,如果local參數是檔案,則本地傳輸到遠端;如果是目錄,則遠端傳輸到本地
* @param remoteIp 遠端主機IP或hostname
* @param port 遠端主機端口号
* @param user 遠端主機使用者名
* @param password 遠端主機對應密碼
* @param local 本地主機檔案名(本地->遠端);本地主機目錄名(遠端->本地)
* @param remote 遠端主機目錄名(本地->遠端);遠端主機檔案名(遠端->本地)
* @return 傳回0:成功。1:失敗
*/
public static int scpFile(String remoteIp, int port, String user, String password, String local,
String remote) {
Connection con = new Connection(remoteIp, port);
try {
con.connect();
boolean isAuthed = con.authenticateWithPassword(user, password);
if (!isAuthed) {
logger.error("遠端主機" + remoteIp + "使用者名或密碼驗證失敗!");
return SystemGlobal.FAILED;
}
SCPClient scpClient = con.createSCPClient();
File localFile = new File(local);
if (localFile.isFile()) {
if (!localFile.exists()) {
logger.error("本地檔案" + local + "不存在,無法傳輸!");
return SystemGlobal.FAILED;
} else {
try {
SFTPv3Client sftpClient = new SFTPv3Client(con);
sftpClient.mkdir(remote, 0777); //遠端建立目錄
} catch (SFTPException e1) {
logger.info("目錄" + remote + "已存在,無需再建立。");
}
try {
scpClient.put(local, remote, "0777");
} catch (IOException e2) {
logger.error("路徑" + remote + "不是一個檔案夾。");
return SystemGlobal.FAILED;
}
String filename = local.substring(local.lastIndexOf('/') + 1);
Session session = con.openSession();
session.execCommand("ls -l " + remote + "/" + filename);
InputStream is = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
br.close();
is.close();
session.close();
logger.info("上傳到遠端主機上的檔案為:" + line);
if (!TaskUtil.isStrEmpty(line)) {
return SystemGlobal.SUCCESS;
}
}
} else {
if (!localFile.exists()) {
localFile.mkdirs();
}
scpClient.get(remote, local);
String filename = remote.substring(remote.lastIndexOf('/') + 1);
if (new File(local + "/" + filename).exists()) {
return SystemGlobal.SUCCESS;
}
}
} catch (Exception e) {
e.printStackTrace();
}
con.close();
return SystemGlobal.FAILED;
}
}
捐助開發者
在興趣的驅動下,寫一個
免費
的東西,有欣喜,也還有汗水,希望你喜歡我的作品,同時也能支援一下。 當然,有錢捧個錢場(右上角的愛心标志,支援支付寶和PayPal捐助),沒錢捧個人場,謝謝各位。

謝謝您的贊助,我會做的更好!