title: telnet from java
body: <p>I am trying to connect to remote linux system from another linux system through telnet using java code as below:</p>
  
  <pre><code>public static void main(String[] args) throws InterruptedException
  {
      // TODO Auto-generated method stub  /usr/bin/telnet
      try
      {
          String line, commandInput;
          ProcessBuilder telnetProcessBuilder = new ProcessBuilder("/bin/bash");
          telnetProcessBuilder.redirectErrorStream(true);
          Process telnetProcess = telnetProcessBuilder.start();
          BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream()));
          BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream()));
          commandInput = "telnet &lt;hostname&gt; -l &lt;username&gt;\n";
          output.write(commandInput);
          output.flush();
          commandInput = "&lt;password&gt;\n";
          output.write(commandInput);
          output.flush();
          commandInput = "ls -l\n";
          output.write(commandInput);
          output.flush();
          commandInput = "pwd\n";
          output.write(commandInput);
          output.flush();
          commandInput = "exit\n";
          output.write(commandInput);
          output.flush();
          commandInput = "uname -a\n";
          output.write(commandInput);
          output.flush();
          commandInput = "exit\n";
          output.write(commandInput);
          output.flush();
          while((line = input.readLine())!= null)
              System.out.println(line);
          //telnetProcess.destroy();
      }
      catch (IOException e)
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>I am able to connect to remote machine and execute the commands before first exit and it logout from remote machine when first exit comes. Now, the problem is i am not able to execute commands after 1st exit even if its exit command from /bin/bash, which will finish the process execution with code 0. And if i destroy the process after 1st exit the BufferedReader and BufferedWriter won't work which generally works if process exits with code 0. I am not sure what can cause this the non-execution of commands after 1st exit. Please let me know the answer if anybody already faced it sometime.</p>
  
  <p>Thanks</p>
  
  <p>Ashutosh</p>