2017-07-29 79 views
0

使用Apache Mina,我試圖讓某些用戶運行某些自定義的SSH命令。但我無法弄清楚如何獲取用戶名或CommandFactory中關於用戶的任何類型的信息。Apache Mina:收到命令後獲取用戶的用戶名

現在,我的服務器配置是這樣的:

SshServer sshd = SshServer.setUpDefaultServer(); 
sshd.setPasswordAuthenticator(new SshPasswordAuthenticator()); 
sshd.setPort(localServerPort); 
sshd.setCommandFactory(new ScpCommandFactory()); 
sshd.setShellFactory(new SshShellFactory()); 
sshd.setSessionFactory(new SshSessionFactory()); 
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("my.pem").getAbsolutePath())); 
sshd.setFileSystemFactory(new VirtualFileSystemFactory(path.getAbsolutePath())); 
List<NamedFactory<Command>> namedFactoryList = new ArrayList<>(); 
namedFactoryList.add(new SftpSubsystem.Factory()); 
sshd.setSubsystemFactories(namedFactoryList); 

這是我SshShellFactory類的樣子:

import org.apache.sshd.common.Factory; 
import org.apache.sshd.server.session.SessionFactory; 
import org.apache.sshd.server.Command; 
import org.apache.sshd.server.CommandFactory; 


public class SshShellFactory implements CommandFactory, Factory<Command> { 

    @Override 
    public Command createCommand(String command) { 
     return new SshSessionCommandWriter(); 
    } 

    @Override 
    public Command create() { 
     return createCommand("none"); 
    } 
} 

ServerVariables店變量與我的軟件,SshSessionCommandWriter做我/ O操作,並且SshCommandManager解釋在SshSessionCommandWriter中讀取的命令,並向客戶端返回一個值。

如果我能找到一種方式來獲取運行該命令的用戶的用戶名,那對我的用例來說是完美的。我目前在​​和SshPasswordAuthenticator中有此信息,但不在SshShellFactory中。

回答

0

因此,我創建的SshSessionCommandWriter對象必須實現Command接口。該命令接口的合同中有方法public void start(Environment env)。原來用戶名存儲在環境變量裏面:

public class SshSessionCommandWriter implements Command, Runnable { 

    @Override 
    public void start(Environment env) throws IOException { 
     String username = env.getEnv().get(Environment.ENV_USER); 
    } 
}