我真的很困惑在Android工作室中将SSH与JSch连接起来。我想创建一个可以远程SSH的应用程序,如connectBot,但它不仅具有GUI终端。这是我的代码
import com.jcraft.jsch.*;
import com.jcraft.jzlib.*;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.button);
Button exit = (Button) findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
executeRemoteCommand("username","password","hostname", 22);
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Not Connected", Toast.LENGTH_LONG).show();
}
}
});
exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
System.exit(0);
}
});
}
public static String executeRemoteCommand(
String username,
String password,
String hostname,
//String command,
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("mkdir /home/beny/test");
channelssh.connect();
channelssh.disconnect();
return baos.toString();
}
}
当我编译的应用程序被迫关闭时。我的代码有什么问题?有什么建议吗?感谢
答案 0 :(得分:1)
问题可能是,您尝试在GUI线程上执行网络操作。
Android上不允许这样做。
您必须为所有网络操作启动后台线程: