如何在Java中使用Apache Mina Sshd Server设置根目录

gih*_*han 11 java sftp jsch apache-mina

我使用Apache Mina Sshd APIjava中启动本地SFTP服务器.在SFTP客户端我使用Jcraft jsch API创建我的SFTP 客户端.我成功启动了服务器.问题是我想写一些单元测试用例到检查客户端是否可以将某些文件放入服务器的根目录.目前我的SFTP服务器没有任何根目录.所以我想知道是否有任何方法来设置服务器的根目录.

例如:C:\ sftp 如何将此路径设置为我的服务器根目录.然后,客户端每次与服务器连接时都可以读取和写入文件.谢谢.

public class SftpServerStarter {
	
	private SshServer sshd;
	private final static Logger logger = LoggerFactory.getLogger(SftpServerStarter.class);
	
	public void start(){
		
		
		sshd = SshServer.setUpDefaultServer();
		sshd.setPort(22);
		sshd.setHost("localhost");
		
        sshd.setPasswordAuthenticator(new MyPasswordAuthenticator());
        sshd.setPublickeyAuthenticator(new MyPublickeyAuthenticator());
        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
        sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystem.Factory()));
        sshd.setCommandFactory(new ScpCommandFactory());
        
        

        try {
        	logger.info("Starting ...");
			sshd.start();
			logger.info("Started");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("Can not Start Server");
		}
	}
	
}
Run Code Online (Sandbox Code Playgroud)

小智 8

在更新的 sshd 版本中,您可以使用org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory它并将其SshServer通过 method提供给实例setFileSystemFactory

片段:

VirtualFileSystemFactory fileSystemFactory = new VirtualFileSystemFactory();
fileSystemFactory.setDefaultHomeDir("home.directory");
sshd.setFileSystemFactory(fileSystemFactory)
Run Code Online (Sandbox Code Playgroud)


Tha*_*han 6

在默认情况下,它从名为的 System 属性中获取根路径 user.dir

序来改变这种情况,您可以覆盖getVirtualUserDir()NativeFileSystemView和返回路径中。

    sshd.setFileSystemFactory(new NativeFileSystemFactory() {
        @Override
        public FileSystemView createFileSystemView(final Session session) {
            return new NativeFileSystemView(session.getUsername(), false) {
                @Override
                public String getVirtualUserDir() {
                    return  "C:\\MyRoot";
                }
            };
        };
    });
Run Code Online (Sandbox Code Playgroud)