Search code examples
javasshjschapache-mina

Implement SSH command to return a contents of a file in Apache Mina


I have created an SSH server which is opening cmd. When I connect with Putty cmd is open and for example, if I write dir (which is the command that I put in the code) everything is okay.

Now, my question is: How to create some API (for example if i write: hello like a command) to return some file content.

I want to achieve this: 1. Connect with Putty to the server 2. write "hello" for example 3. print in putty console content of some file.

Here is the code for my SSH server. I am using apache-mina library:

public class SshServerMock {

public static void server() throws IOException, JSchException, SftpException {
    SshServer sshd = SshServer.setUpDefaultServer();

    sshd.setHost("127.0.0.1");
    sshd.setPort(22);

    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("C://hostkey.ser")));
    sshd.setPasswordAuthenticator(new PasswordAuthenticator() {

        @Override
        public boolean authenticate(String u, String p, ServerSession s) {              
            return ("root".equals(u) && "iskratel".equals(p));
        }   

    });

    sshd.setShellFactory(new ProcessShellFactory(new String[] { "cmd.exe" }));
    sshd.start();
    try {
        Thread.sleep(100000000000l);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }


}

}


Solution

  • By executing cmd, you start a Windows shell. At that moment the session gets out of control of your code. You cannot add a command to the shell using your Java code.

    But obviously, you can add the command in the Windows shell. Just create a hello.bat batch file and make sure it's in Windows PATH for an easy access. Make sure the PATH is set for the local ("local" as of the server) account that runs the session.

    The hello.bat batch file can be as trivial as:

    type c:\path\to\file.txt
    

    Note that allowing an user to run cmd.exe can be pretty dangerous. So make sure you know, what you are doing.


    In my opinion, you should implement the CommandFactory interface.

    Make it create a Command that feed the "file" to the stream provided by setOutputStream.

    On client side, with JSch library, use this code:
    http://www.jcraft.com/jsch/examples/Exec.java.html