我試圖通過使用JSch庫的SSH協議執行多個命令。但我似乎卡住了,找不到任何解決方案。 setCommand()
方法只能在每個會話中執行單個命令。但我想按照Android平臺上的connectbot應用程序的順序執行這些命令。到目前爲止,我的代碼是:通過Jsch Shell執行多個命令
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());
}
}
代碼似乎可以連接到服務器,但我認爲有一些問題,輸入和輸出數組緩衝區,因爲有沒有輸出。有人可以請指導我如何妥善處理輸入和輸出到服務器以獲得所需的輸出?
這是怎麼完成的任何例子? – Pixie 2016-06-02 15:49:14