zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java scp传输文件

JAVA文件 传输 scp
2023-06-13 09:11:15 时间

大家好,又见面了,我是你们的朋友全栈君。

 <dependency>
     <groupId>ch.ethz.ganymed</groupId>  
    <artifactId>ganymed-ssh2</artifactId>  
    <version>build210</version>  
  </dependency>
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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;
public class SCPUtil {
public static final String LOCALPATH = "";
public static final String REMOTEFILEPATH = "";
public static final String REMOTEIP = "";
public static final String USERNAME = "";
public static final String PASSWORD = "";
/**
* 远程文件传输,如果local参数是文件,则本地传输到远程;如果是目录,则远程传输到本地
* 
* @param remoteIp
*            远程主机IP或hostname
* @param user
*            远程主机用户名
* @param password
*            远程主机对应密码
* @param local
*            本地主机文件名(本地->远程);本地主机目录名(远程->本地)
* @param remote
*            远程主机目录名(本地->远程);远程主机文件名(远程->本地)
* @return 返回true:成功。false:失败
*/
public static boolean scpFile(String remoteIp, String user,
String password, String local, String remote) {
Connection con = new Connection(remoteIp);
try {
con.connect();
boolean isAuthed = con.authenticateWithPassword(user, password);
if (!isAuthed) {
//logger.error("远程主机" + remoteIp + "用户名或密码验证失败!");
return false;
}
SCPClient scpClient = con.createSCPClient();
File localFile = new File(local);
if (localFile.isFile()) {
if (!localFile.exists()) {
//logger.error("本地文件" + local + "不存在,无法传输!");
return false;
} 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 true;
}
// 上传到远程主机上的文件
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();
if (!StringUtils.isEmpty(line)) {
return true;
}
}
} else {
if (!localFile.exists()) {
localFile.mkdirs();
}
scpClient.get(remote, local);
String filename = remote.substring(remote.lastIndexOf('/') + 1);
if (new File(local + "/" + filename).exists()) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
con.close();
return false;
}
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/171994.html原文链接:https://javaforall.cn