如何将文件写入 Apache SSHD 服务器?

How to write file into Apache SSHD server?

解释:

我正在为我的同事构建一个测试工具。我有几个“模拟”内存后端,它们将需要用于 运行 集成测试。

因此,我需要 运行 SSH 服务器能够 upload/download 一个文件。

基本用例如下:

问题:

我写了 Apache SSHD 服务器:

服务器实现示例SshServer.java:

package com.example.sshd;

import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.scp.ScpCommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.file.Files;

public class SSHServer {

    private SshServer sshServer;
    private static final Logger logger = LoggerFactory.getLogger(SSHServer.class);

    public SSHServer() throws IOException {
        sshServer = SshServer.setUpDefaultServer();
        sshServer.setHost("127.0.0.1");
        sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Files.createTempFile("host_file", ".ser").toAbsolutePath()));
        sshServer.setCommandFactory(new ScpCommandFactory());
        sshServer.setPasswordAuthenticator((username, password, serverSession) -> {
            logger.debug("authenticating: {} password: {}", username, password);
            return username != null && "changeit".equals(password);
        });
    }

    public void startServer() throws IOException{
        sshServer.start();
    }

    public void stopServer() throws IOException {
        sshServer.stop();
    }
}

我试过了:

到目前为止我找不到答案。我找到了这个 ,看起来我也需要有 SSH 客户端。我在正确的轨道上吗?

显然是的。

因为我没有 SSH 客户端,所以我必须同时创建客户端和服务器。

Kotlin 文件上传示例:

fun upload(file: File) {
    val creator = ScpClientCreator.instance()
    val scpClient = creator.createScpClient(session())
    scpClient.upload(Paths.get(file.absolutePath), file.name)
}

SSH 服务器创建:

fun setupServer(host: String, port: Int, rootDir: File, userName: String, pwd: String): SshServer {
    val sshd = SshServer.setUpDefaultServer()
    sshd.keyPairProvider = SimpleGeneratorHostKeyProvider(File(rootDir, "sshd_key.ser").toPath())
    sshd.fileSystemFactory = VirtualFileSystemFactory(Paths.get(rootDir.absolutePath))
    sshd.port = port
    sshd.host = host
    sshd.passwordAuthenticator = PasswordAuthenticator { username: String, password: String, _: ServerSession? -> username == userName && password == pwd }
    sshd.commandFactory = ScpCommandFactory()
    val factoryList: MutableList<SubsystemFactory> = ArrayList()
    factoryList.add(SftpSubsystemFactory())
    sshd.subsystemFactories = factoryList
    return sshd
}

SSH 客户端创建:

fun setupClient(): SshClient {
    return SshClient.setUpDefaultClient()
}

// Session for scp client
fun session(): ClientSession {
    val session = client.connect(userName, server.host, server.port).verify().session
    session.addPasswordIdentity(password)
    session.auth().verify().isSuccess
    return session
}