如需转载分享,请标明出处,且不用于盈利为目的,谢谢合作!
使用java的sftp方式实现Linux服务器之间文件传输(复制)
1.pom.xml中添加依赖:
<!--sftp依赖包-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2.新建类SftpUtil.java
package com.file.util;
import com.jcraft.jsch.*;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
public class SftpUtil {
/**
* 连接sftp
*
* @param host 主机
* @param port 端口
* @param username 用户名
* @param password 密码
* @return
*/
public static ChannelSftp connect(String host, int port, String username,
String password) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session创建成功");
sshSession.setPassword(password);
System.out.println("密码输入成功");
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
System.out.println("链接参数设置成功");
sshSession.setConfig(sshConfig);
sshSession.connect();
System.out.println("Session已连接");
Channel channel = sshSession.openChannel("sftp");
channel.connect(