I'm really confusing to connect SSH with JSch in Android studio. I want to create an app that can remote SSH like connectBot but it has a GUI not only terminal. Here's my code
import com.jcraft.jsch.*;
import com.jcraft.jzlib.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button);
Button exit = (Button) findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
executeRemoteCommand("username","password","hostname", 22);
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Not Connected", Toast.LENGTH_LONG).show();
}
}
});
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.exit(0);
}
});
}
public static String executeRemoteCommand(
String username,
String password,
String hostname,
//String command,
int port) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, port);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
// SSH Channel
ChannelExec channelssh = (ChannelExec)
session.openChannel("exec");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channelssh.setOutputStream(baos);
// Execute command
channelssh.setCommand("mkdir /home/beny/test");
channelssh.connect();
channelssh.disconnect();
return baos.toString();
}
}
When I'm compiled app has forced close. Whats wrong with my code? Any suggestion? Thanks