我试图使用 JSch 库通过 SSH 协议执行多个命令。但我似乎陷入困境,找不到任何解决方案。这setCommand()
方法每个会话只能执行单个命令。但我想像Android平台上的connectbot应用程序一样顺序执行命令。到目前为止我的代码是:
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());
}
}
该代码似乎已连接到服务器,但我认为输入和输出数组缓冲区存在一些问题,因为根本没有输出。有人可以指导我如何正确处理服务器的输入和输出以获得所需的输出吗?
如果您不必区分各个命令的输入或输出,Aaron 的答案(给出一行中的所有命令,用\n
or ;
)很好。
如果您必须单独处理它们,或者在前面的命令完成之前不知道后面的命令:您可以打开多个exec-频道 http://epaul.github.com/jsch-documentation/simple.javadoc/index.html?com/jcraft/jsch/ChannelExec.html在同一个会话(即连接)上,一个接着一个(即在前一个会话关闭之后)。每个人都有自己的命令。 (但他们不共享环境,所以cd
第一个命令中的命令对后面的命令没有影响。)
您只需小心地拥有Session http://epaul.github.com/jsch-documentation/simple.javadoc/index.html?com/jcraft/jsch/Session.html对象周围,而不是为每个命令创建一个新对象。
另一种选择是外壳通道 http://epaul.github.com/jsch-documentation/simple.javadoc/index.html?com/jcraft/jsch/ChannelShell.html,然后将各个命令作为输入传递到远程 shell(即通过流)。但是,您必须注意不要将一个命令的输入与下一个命令混合(即,只有当您知道这些命令正在做什么,或者您有一个交互式用户可以同时提供该命令的输入和下一个命令,并知道何时使用哪个命令。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)