Basic SSH connection via JSCH on android

孤人 提交于 2019-12-06 12:24:46

问题


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.


回答1:


Ok here we go, your code is okay, but some little errors are in.. let me correct this, you have to implement the button right and some little changes and it will work:

MainActivity:

    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);


    Button btn = (Button) view.findViewById(R.id.button);
            btn.setOnClickListener(new View.OnClickListener() {
                //start execution of ssh commands
                @Override
                public void onClick(View v){
                    new AsyncTask<Integer, Void, Void>(){
                        @Override
                        protected Void doInBackground(Integer... params) {
                            try {
                                executeSSHcommand();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return null;
                        }
                    }.execute(1);                       
                }
            });
}

    public void executeSSHcommand(){
        String user = "xxx";
        String password = "xxx";
        String host = "192.168.xxx.xxx";
        int port=22;
        try{

            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(10000);
            session.connect();
            ChannelExec channel = (ChannelExec)session.openChannel("exec");
            channel.setCommand("your ssh command here");
            channel.connect();
            channel.disconnect();
            // show success in UI with a snackbar alternatively use a toast
            Snackbar.make(getActivity().findViewById(android.R.id.content),  
                    "Success!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
        catch(JSchException e){
            // show the error in the UI 
            Snackbar.make(getActivity().findViewById(android.R.id.content), 
                     "Check WIFI or Server! Error : "+e.getMessage(),
                     Snackbar.LENGTH_LONG)
                     .setDuration(20000).setAction("Action", null).show();
        }
    }
}

additional you can delete the line " android:onClick="onCLick" " in your layout.xml

at my project this is working just fine even without the delay. of curse you need internet permission in manifest file. but i think this permission will grantet immediately on start of the application.
hope it helps, sometimes little things make a difference.

kind regards
chwzr



来源:https://stackoverflow.com/questions/41050989/basic-ssh-connection-via-jsch-on-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!