5

我设法通过 ssh 和 Jsch 执行了一个命令,但是当我尝试执行第二个命令时它失败了

对于调试,我将这个问题归结为以下几行:

import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class Exec {

    public static void test(Session session) throws Exception {
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand("pwd");

        channel.setInputStream(null);

        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();

        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
    }

    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();         
            Session session = jsch.getSession("nck", "127.0.0.1", 22);          
            session.setPassword("asd");         
            session.setConfig("StrictHostKeyChecking", "no");           
            session.connect();

            test(session); // This one succeeds with exit-status: 0         
            test(session); // This one fails with exit-status: 255

            session.disconnect();
        } catch (Exception e) {
            //
        }
    }
}

这主要是官方的 Exec 示例,但这给了我这个输出:

/home/nck
exit-status: 0
exit-status: 255

第一个命令成功执行第二个没有。

有任何想法吗 ?

4

6 回答 6

7

这是一个基于@krishna 回答的完整的 Java 类:

/**
 * Run several ssh commands in a single JSch session
 */
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.io.*;

class SshMultiCommands
{
   public static void main(String[] args) throws Exception
   {
      JSch jsch = new JSch();
      String user = "user";            //CHANGE ME
      String host = "192.168.222.157"; //CHANGE ME
      String passwd = "password";      //CHANGE ME
      int port = 22;    
      Session session = jsch.getSession(user, host, port);
      session.setPassword(passwd);

      session.setConfig("StrictHostKeyChecking", "no");

      session.connect();

      Channel channel = session.openChannel("shell");
      OutputStream ops = channel.getOutputStream();
      PrintStream ps = new PrintStream(ops, true);

      channel.connect();
      InputStream input = channel.getInputStream();

      //commands
      ps.println("ls -lag");
      ps.println("cd /etc");
      ps.println("ls");
      ps.println("exit");
      ps.close();

      printResult(input, channel);

      channel.disconnect();
      session.disconnect();
   }

   /**
    * @param input
    * @param channel
    */
   private static void printResult(InputStream input,
                                   Channel channel) throws Exception
   {
      int SIZE = 1024;
      byte[] tmp = new byte[SIZE];
      while (true)
      {
         while (input.available() > 0)
         {
            int i = input.read(tmp, 0, SIZE);
            if(i < 0)
               break;
             System.out.print(new String(tmp, 0, i));
         }
         if(channel.isClosed())
         {
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
         }
         try
         {
            Thread.sleep(300);
         }
         catch (Exception ee)
         {
         }
      }
   }
}
于 2013-05-24T03:18:19.450 回答
4

嘿,我对 jsch 和 Ubuntu 有完全相同的问题。(如何)你解决了吗?为每次执行创建一个新会话会占用太多时间?目前我捕获了 jsch 异常并搜索“会话未关闭”,然后我重新连接会话并再次执行命令。这有效,但不是一个好的解决方案。

编辑:我现在用错误的方式解决了我的问题

channel = session.openChannel("shell");

而不是“执行”。

于 2012-03-30T11:07:02.913 回答
3

您可以使用 shell 执行多个命令。以下是通过 shell 执行命令的代码。

Channel channel=session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);

channel.connect();
ps.println("mkdir folder"); 
ps.println("dir");
//give commands to be executed inside println.and can have any no of commands sent.
ps.close();

InputStream in=channel.getInputStream();
byte[] bt=new byte[1024];

while(true) {
    while(in.available()>0) {
        int i=in.read(bt, 0, 1024);
        if(i<0)
            break;
        String str=new String(bt, 0, i);

        //displays the output of the command executed.
        System.out.print(str);
    }
    if(channel.isClosed()) 
        break;

    Thread.sleep(1000);
    channel.disconnect();
    session.disconnect();   
}
于 2013-01-03T09:41:30.993 回答
2

如果你想使用 exec。您可以通过在命令中添加分号 (;) 来运行多个命令

像:

pwd;ls- -l; 
cd foldername

((ChannelExec) channel).setCommand("pwd;ls -l; cd foldername");
于 2014-10-21T13:31:03.943 回答
1

我使用了完全相同的代码,并且有时在读取我通过 ssh 执行的脚本的输出时遇到了问题。有时该程序缺少所有内容,有时仅缺少部分内容。我通过更改嵌套循环中的 if(channel.isclosed) 解决了我的问题。这是新代码

while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            System.out.print(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
             if(in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                System.out.print(new String(tmp, 0, i));
             } 
            System.out.println("exit-status: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
}
于 2012-04-23T13:13:56.390 回答
0

这不是 jsch 中的错误,而是我的 ssh 服务器的错误(cygwin - 我敢打赌我配置错误......)

编辑:嗯,我对 Ubuntu 的 jsch 有同样的问题......很奇怪

猜猜作为workarround,我必须为每个查询打开一个新会话。

于 2011-08-27T11:13:22.470 回答