As the fellow user from this question and this tutorial explain, I'm trying to setup a simples ssh connection to perform a single command on a app. It dosen't even need to wait for any response.
Here is the code:
Main Activity: package com.example.lucas.shutdown;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onCLick(View v){
new AsyncTask<Integer, Void, Void>(){
@Override
protected Void doInBackground(Integer... params) {
try {
executeRemoteShutdown();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(1);
}
public void executeRemoteShutdown(){
String user = "ssh";
String password = "123";
String host = "192.168.1.4";
int port=22;
try{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = (ChannelExec) session.openChannel("exec");
((ChannelExec) channel).setCommand("shutdown /s");
channel.connect();
try{
Thread.sleep(1000);
}catch(Exception ee){}
channel.disconnect();
session.disconnect();
}
catch(Exception e){}
}
}
The button that performs the action:
<Button
android:text="Shutdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/button"
android:onClick="onCLick" />
This same method executeRemoteShutdown()
already works on a diferent program in pure java, however the thing I'm having trouble with is that the conection and comand execution seems to never happen. I followed the recomendations from the question I linked above to run the ssh method on a diferent thread, add a delay to wait for the command be executed on the host before the method finishes and gave internet permission on the manifest file.