I got this to work as a standalone program so far, it should be relatively straightforward to put it into android.
build.gradle
android {
. . .
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
}
dependencies {
. . .
compile group: 'org.apache.sshd', name: 'sshd-core', version: '0.6.0'
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.6.2'
compile "org.bouncycastle:bcprov-jdk16:1.46" // only needed if you're in android
}
java class
public class Server {
static public void main(String []argv) {
System.out.println("Hello Server");
Server server = new Server();
server.doAll();
System.out.println("Goodbye Server");
}
public void doAll() {
startSSHServer();
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void startSSHServer() {
int port = 8888;
SshServer sshd = SshServer.setUpDefaultServer();
sshd.setPort(port);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(
"src/test/resources/hostkey.ser"));
sshd.setSubsystemFactories(Arrays
.<NamedFactory<Command>> asList(new SftpSubsystem.Factory()));
sshd.setCommandFactory(new ScpCommandFactory());
sshd.setShellFactory(new ProcessShellFactory(new String[] { "/system/bin/sh", "-i", "-l" })); // necessary if you want to type commands over ssh
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
@Override
public boolean authenticate(String u, String p, ServerSession s) {
return ("sftptest".equals(u) && "sftptest".equals(p));
}
});
try {
sshd.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The server will start and run for 50 seconds, given by the sleep time.
Connect to it using ssh sftptest@localhost -p 8888
Putting it into an activity would look like this
public class MainActivity extends AppCompatActivity {
private Button startButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startServer();
}
});
}
private void startServer() {
Thread th = new Thread(new Runnable() {
@Override
public void run() {
Server server = new Server();
Log.i("SSHD","Start ssh");
server.startSSHServer();
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("SSHD","End ssh");
}
});
th.start();
}
}
The server may run for 60 seconds here.
To discover the ip address of the phone use adb shell 'ip addr'
To connect to android it's a slightly longer command line
ssh sftptest@ip.address.of.phone -o UserKnownHostsFile=/dev/null -p 8888 -T