我试图通过这个简单的例子来创造一些东西:
我只是想看看我是否可以使用SSH从我的Android手机连接到Linux服务器,但它不起作用...
这是我的主要代码:
package com.example.ssh;
import java.util.Properties;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try
{
JSch jsch = new JSch();
Session session = jsch.getSession("root","192.168.0.26", 22);
session.setPassword("xxxxx");
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么 ?我没有错误消息,我的Linux上没有看到任何SSH连接.我添加了库jsch和jzlib.我没有问题与putty会话连接.
编辑1:事实上,我发现了一个错误,解释了为什么即使我不知道如何解决问题它也不起作用.错误是:
android.os.NetworkOnMainThreadException
所以它似乎意味着应用程序无法在其主线程上执行网络操作...
我正在尝试使用来自Android和JS的SSH在Linux服务器上执行命令.
据我所知,我正在连接到服务器,但当我尝试检索命令的结果时,我什么都没得到.
连接到服务器:
public class SSHCommand {
public static String executeRemoteCommand(
String username,
String password,
String hostname,
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("ls");
channelssh.connect();
channelssh.disconnect();
return baos.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
检索数据:
public class MainActivity extends Activity { …Run Code Online (Sandbox Code Playgroud)