在Android上通过JSCH进行基本的SSH连接 [英] Basic SSH connection via JSCH on android

查看:199
本文介绍了在Android上通过JSCH进行基本的SSH连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为此问题和此

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.

这是代码:

主要活动: 包com.example.lucas.shutdown;

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){}
    }
}

执行操作的按钮:

    <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" />

同样的方法executeRemoteShutdown()在纯Java中的不同程序上已经可以使用,但是我遇到的麻烦是连接和命令执行似乎从未发生.我遵循上面链接的问题的建议,在不同的线程上运行ssh方法,添加了延迟,以等待该方法完成之前在主机上执行该命令,并在清单文件上授予Internet权限.

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.

推荐答案

好,我们走了, 您的代码还可以,但是有一些小错误..让我纠正一下, 您必须在右侧实施按钮并进行一些小的更改,它才能正常工作:

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:

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

另外,您可以在您的layout.xml中删除"android:onClick ="onCLick"行

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

在我的项目中,即使没有延迟,它也可以正常工作.诅咒您需要清单文件中的Internet权限.但我认为此许可将在应用程序启动时立即授予.
希望它能有所帮助,有时一点点的事情都会有所作为.

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.

亲切的问候
chwzr

kind regards
chwzr

这篇关于在Android上通过JSCH进行基本的SSH连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆