title: Jsch - One Session Multiple Channels
body: <p>I managed to execute a single command through ssh with Jsch but when i try to execute a second command it fails</p>
  
  <p>For debugging i brought this problem down to this lines:</p>
  
  <pre><code>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() &gt; 0) {
                  int i = in.read(tmp, 0, 1024);
                  if (i &lt; 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) {
              //
          }
      }
  }
  </code></pre>
  
  <p>This is mostly the official Exec example but this gives me this output:</p>
  
  <pre><code>/home/nck
  exit-status: 0
  exit-status: 255
  </code></pre>
  
  <p>The first command is executed succesfully the second doesnt.</p>
  
  <p>Any Ideas ?</p>