Ich habe versucht, mehrere Befehle über das SSH-Protokoll unter Verwendung der JSch-Bibliothek auszuführen. Aber ich scheine festzustecken und kann keine Lösung finden. Die setCommand()
Methode kann nur einzelne Befehle pro Sitzung ausführen. Ich möchte aber die Befehle sequentiell ausführen, genau wie die connectbot-App auf der Android-Plattform. Bis jetzt ist mein Code:
package com.example.ssh;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class ExampleSSH extends Activity {
/** Called when the activity is first created. */
EditText command;
TextView result;
Session session;
ByteArrayOutputStream baos;
ByteArrayInputStream bais;
Channel channel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bais = new ByteArrayInputStream(new byte[1000]);
command = (EditText) findViewById(R.id.editText1);
result = (TextView) findViewById(R.id.terminal);
}
public void onSSH(View v){
String username = "xxxyyyzzz";
String password = "aaabbbccc";
String host = "192.168.1.1"; // sample ip address
if(command.getText().toString() != ""){
JSch jsch = new JSch();
try {
session = jsch.getSession(username, host, 22);
session.setPassword(password);
Properties properties = new Properties();
properties.put("StrictHostKeyChecking", "no");
session.setConfig(properties);
session.connect(30000);
channel = session.openChannel("shell");
channel.setInputStream(bais);
channel.setOutputStream(baos);
channel.connect();
} catch (JSchException e) {
// TODO Auto-generated catch block
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(this, "Command cannot be empty !", Toast.LENGTH_LONG).show();
}
}
public void onCommand(View v){
try {
bais.read(command.getText().toString().getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
baos = new ByteArrayOutputStream();
channel.setOutputStream(baos);
result.setText(baos.toString());
}
}
Der Code scheint mit dem Server verbunden zu werden, aber ich denke, dass es ein Problem mit den Eingabe- und Ausgabe-Array-Puffern gibt, da es überhaupt keine Ausgabe gibt. Kann mir bitte jemand erklären, wie man die Ein- und Ausgabe zum und vom Server richtig handhabt, um die gewünschte Ausgabe zu erhalten?