From ab69189d5becb126544ae79e8d59b12cf4d70f9b Mon Sep 17 00:00:00 2001 From: LamGC Date: Fri, 10 Sep 2021 02:33:33 +0800 Subject: [PATCH] =?UTF-8?q?feat(sftp):=20Sftp=20=E7=8E=B0=E5=9C=A8?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E8=8E=B7=E5=8F=96=E7=94=A8=E6=88=B7=E4=B8=BB?= =?UTF-8?q?=E7=9B=AE=E5=BD=95.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 鉴于当前尚不支持使用"~"指向用户主目录, 为此提供解决方法. --- .../sentry/oci/compute/ssh/SftpSession.java | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/main/java/net/lamgc/oracle/sentry/oci/compute/ssh/SftpSession.java b/src/main/java/net/lamgc/oracle/sentry/oci/compute/ssh/SftpSession.java index 2b24ea3..e1084ad 100644 --- a/src/main/java/net/lamgc/oracle/sentry/oci/compute/ssh/SftpSession.java +++ b/src/main/java/net/lamgc/oracle/sentry/oci/compute/ssh/SftpSession.java @@ -1,10 +1,12 @@ package net.lamgc.oracle.sentry.oci.compute.ssh; +import net.lamgc.oracle.sentry.common.LazyLoader; import org.apache.sshd.sftp.client.SftpClient; import org.apache.sshd.sftp.common.SftpConstants; import org.apache.sshd.sftp.common.SftpException; import java.io.*; +import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.NoSuchFileException; import java.util.HashSet; @@ -30,6 +32,7 @@ public class SftpSession implements Closeable { } private final SftpClient sftpClient; + private final LazyLoader userHome; /** * 创建 Sftp 会话. @@ -37,6 +40,20 @@ public class SftpSession implements Closeable { */ SftpSession(SftpClient sftpClient) { this.sftpClient = sftpClient; + this.userHome = new LazyLoader<>(() -> { + try { + CommandExecSession echoHOME = new CommandExecSession(sftpClient.getSession().createExecChannel("echo $HOME")); + ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); + echoHOME.setOut(outBuffer); + echoHOME.exec(); + if (echoHOME.exitCode() != null && echoHOME.exitCode() == 0) { + return outBuffer.toString(StandardCharsets.UTF_8).trim(); + } + throw new IOException("Command execution failed.(ExitCode: " + echoHOME.exitCode() + ")"); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); } /** @@ -247,4 +264,17 @@ public class SftpSession implements Closeable { sftpClient.close(); } + /** + * 获取用户主目录. + * @return 返回用户主目录, 例如: "/root", 末尾无符号. + * @throws IOException 如果操作失败, 则抛出异常. + */ + public String getUserHome() throws IOException { + try { + return userHome.getInstance(); + } catch (RuntimeException e) { + throw (IOException) e.getCause(); + } + } + }