SFTP上传文件,下载文件尝试
注意: 要在pom.xml中添加JSch 的依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<!--<version>0.1.55</version>--> <!-- 不添加版本,默认最新版本 -->
</dependency>
- 具体代码如下:
package com.xxx.xxx.xxxxxx.xxx.xxx;
import com.jcraft.jsch.*;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.*;
/**
* @author Liang
* @version 1.0
* @date 2022/5/24 9:39
*/
@Log4j2
public class SFTPPutFileTest {
private static final String hostname = "xx.x.xxx.xxx"; // ip地址
private static final String port = "22"; //端口号
private static final String sshUser = "xxxxx"; //用户名
private static final String sshPass = "xxxxxx"; // 密码
/**
* 上传文件
* @throws Exception
*/
@Test
public void putFileToServer() throws Exception {
File uploadFile = new File("/home/sftp/test.zip");// 要上传的文件
JSch jSch = new JSch();
String filePath = "/home/sftp/"; // 文件上传的地址
Session session = null;
ChannelSftp sftp = null;
try {
session = jSch.getSession(sshUser, hostname, Integer.parseInt(port));
session.setPassword(sshPass);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no"); // 设置ssh安全级别
session.setConfig(sshConfig); //设置参数
session.connect(); //建立连接
// 获取上传的管道
Channel channel = session.openChannel("sftp");
channel.connect(); // 建立sftp通道连接
sftp = (ChannelSftp) channel;
//发送文件、

最低0.47元/天 解锁文章
2376

被折叠的 条评论
为什么被折叠?



