123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- package sys.sc.opplugin.utils;
- /**
- * @author cjz
- * @date 2024/9/9 17:05
- * @description:连接服务器获取sftp,工具类
- */
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.Session;
- import com.jcraft.jsch.SftpException;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- public class SftpClient {
- private String host;
- private String usernmae;
- private String password;
- private int port;
- private Session session;
- private ChannelSftp sftpChannel;
- public SftpClient(String host, String user, String password,int port) {
- this.host = host;
- this.usernmae = user;
- this.password = password;
- this.port=port;
- }
- // 连接到 SFTP 服务器
- public void connect() throws Exception {
- JSch jsch = new JSch();
- session = jsch.getSession(usernmae, host, port);
- session.setPassword(password);
- session.setConfig("StrictHostKeyChecking", "no");
- session.connect();
- sftpChannel = (ChannelSftp) session.openChannel("sftp");
- sftpChannel.connect();
- }
- //根据服务器路径读取文件,返回文件流
- public InputStream fileInputStream(String remoteFilePath) throws SftpException {
- InputStream inputStream = sftpChannel.get(remoteFilePath);
- return inputStream;
- }
- //上传文件到服务器路径,
- public void fileCreat(String localFilePath,String remoteFilePath) throws SftpException {
- //本地服务器传到服务器文件
- sftpChannel.put(localFilePath,remoteFilePath);
- }
- // 断开连接
- public void disconnect() {
- if (sftpChannel != null && sftpChannel.isConnected()) {
- sftpChannel.disconnect();
- }
- if (session != null && session.isConnected()) {
- session.disconnect();
- }
- }
- public ChannelSftp getSftpChannel() {
- return sftpChannel;
- }
- }
|