From dd1ec90fd4e070d0103c1daa4125c0e41a98a9c2 Mon Sep 17 00:00:00 2001 From: Looly Date: Wed, 24 Jan 2024 10:09:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DSshjSftpSession=E5=85=B3?= =?UTF-8?q?=E9=97=AD=E5=AF=BC=E8=87=B4=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../extra/ssh/engine/sshj/SshjSftp.java | 44 ++++++++++++++----- 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/hutool-extra/src/main/java/org/dromara/hutool/extra/ssh/engine/sshj/SshjSftp.java b/hutool-extra/src/main/java/org/dromara/hutool/extra/ssh/engine/sshj/SshjSftp.java index 6b2993df9..7fbf1197e 100644 --- a/hutool-extra/src/main/java/org/dromara/hutool/extra/ssh/engine/sshj/SshjSftp.java +++ b/hutool-extra/src/main/java/org/dromara/hutool/extra/ssh/engine/sshj/SshjSftp.java @@ -89,6 +89,7 @@ public class SshjSftp extends AbstractFtp { private SSHClient ssh; private SFTPClient sftp; + private Session session; /** * 构造 @@ -120,7 +121,9 @@ public class SshjSftp extends AbstractFtp { * @since 5.7.18 */ public void init() { - this.ssh = SshjUtil.openClient(this.ftpConfig.getConnector()); + if(null == this.ssh){ + this.ssh = SshjUtil.openClient(this.ftpConfig.getConnector()); + } try { ssh.setRemoteCharset(ftpConfig.getCharset()); @@ -248,12 +251,9 @@ public class SshjSftp extends AbstractFtp { @Override public void close() { - try { - sftp.close(); - ssh.disconnect(); - } catch (final IOException e) { - throw new FtpException(e); - } + IoUtil.closeQuietly(this.session); + IoUtil.closeQuietly(this.sftp); + IoUtil.closeQuietly(this.ssh); } /** @@ -283,16 +283,36 @@ public class SshjSftp extends AbstractFtp { * @since 5.7.19 */ public String command(final String exec) { - Session session = null; + final Session session = this.initSession(); + + Session.Command command = null; try { - session = ssh.startSession(); - final Session.Command command = session.exec(exec); + command = session.exec(exec); final InputStream inputStream = command.getInputStream(); - return IoUtil.read(inputStream, DEFAULT_CHARSET); + return IoUtil.read(inputStream, this.ftpConfig.getCharset()); } catch (final Exception e) { throw new FtpException(e); } finally { - IoUtil.closeQuietly(session); + IoUtil.closeQuietly(command); } } + + /** + * 初始化Session并返回 + * + * @return session + */ + private Session initSession() { + Session session = this.session; + if (null == session || !session.isOpen()) { + IoUtil.closeQuietly(session); + try { + session = this.ssh.startSession(); + } catch (final Exception e) { + throw new FtpException(e); + } + this.session = session; + } + return session; + } }