1 year ago
#335928
carlit
SSH connection not working only on android device
I'm just trying to make a simple ssh connection from my android device, this code works fine from my Android Studio but when I run it on my Android device does not work. it is not able to find the host at all.
I think it has something to do with network but I don't know what. I check all the settings and everything looks normal, the device I want to reach is in my home network and from my router I can see all the devices with proper names and all are reachable, I can ping all of them included my Android device from where I want to run this code.
public class MainActivity2 extends AppCompatActivity {
String host, username, password, command;
Integer port;
TextView shellOutput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
shellOutput = findViewById(R.id.toShowMessage);
host = intent.getStringExtra("host");
port = Integer.parseInt(intent.getStringExtra("port"));
username = intent.getStringExtra("username");
password = intent.getStringExtra("password");
command = intent.getStringExtra("command");
new Thread(new Runnable(){
@Override
public void run() {
try {
executeSSHCommand(host, port, username, password, command);
}
catch (Exception ex) {
ex.printStackTrace();
Snackbar.make(findViewById(R.id.Activity2), R.string.connection_test,
Snackbar.LENGTH_SHORT).show();
}
}
}).start();
}
public void executeSSHCommand(String host, int port, String username, String password, String command) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, 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(command);
channelssh.connect();
while (true) {
if (channelssh.isClosed()) {
break;
}
}
Snackbar.make(findViewById(R.id.Activity2), R.string.connection_success,
Snackbar.LENGTH_SHORT).show();
shellOutput.setText(baos.toString());
channelssh.disconnect();
} catch (JSchException e) {
// show the error in the UI
Snackbar.make(findViewById(R.id.Activity2), R.string.connection_failed + "//" + e.getMessage(),
Snackbar.LENGTH_LONG).show();
}
}
}
java
android
ssh
jsch
0 Answers
Your Answer