开发者社区> 问答> 正文

求救,jsch执行linux命令

jsch执行linux命令的时候,表示一直是在根目录下,cd命令执行不了, 这是我的代码,求大神看看是哪里出了错

public class ShellExecuter {
private static final int BLOCK_SIZE = 1024;
private static Session session;
public ShellExecuter(Session session){
    this.session=session;
}

private static ChannelExec openChannelExec(Session session){
    ChannelExec exec = null;
    try {
        Channel channel = session.openChannel("exec");
        exec = (ChannelExec)channel;
    } catch (JSchException e) {
        e.printStackTrace();
    }
    return exec;
}
public static String execute(String command, Session session) throws Exception{
    ChannelExec exec = openChannelExec(session);
    StringBuffer buffer = executeCommand(command, exec);
    closeChannelExec(exec);
    return buffer.toString();
}
private static StringBuffer executeCommand(String command, ChannelExec exec) throws Exception{
    InputStream inputStream = exec.getInputStream();
    exec.setCommand(command);
    exec.connect();
    StringBuffer buffer = generateResult(inputStream);
    return buffer;
}
private static StringBuffer generateResult(InputStream inputStream) throws IOException{
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream),524288000);
    String line = "";
    while((line=reader.readLine())!=null){
        buffer.append(line).append("<br/>");
      }
    reader.close();
    inputStream.close();
    return buffer;
}

private static void closeChannelExec(ChannelExec channelExec) {
    channelExec.disconnect();
 }
}

展开
收起
杨冬芳 2016-07-14 15:41:37 3038 0
1 条回答
写回答
取消 提交回答
  • IT从业

    android执行Linux命令
    android执行Linux命令
    Linux中后台命令的执行

    2019-07-17 19:56:23
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Alibaba Cloud Linux 3 发布 立即下载
ECS系统指南之Linux系统诊断 立即下载
ECS运维指南 之 Linux系统诊断 立即下载