java - jsch channel gets disconnected when called for the second time -


my requirement connect remote machine via ssh using java . using jsch same. have sequence of commands executed , each command execution depends on output of previous command.

fox example, if executing:

 ls -l  

after login remote machine calling:

runcommand(“ls -l\n”); 

based on output above step need create directory:

runcommand(“mkdir test\n”);  

on executing getting:

com.jcraft.jsch.jschexception: failed send channel request @ com.jcraft.jsch.request.write(request.java:65) @ com.jcraft.jsch.requestptyreq.request(requestptyreq.java:76) @ com.jcraft.jsch.channelsession.sendrequests(channelsession.java:212) @ com.jcraft.jsch.channelshell.start(channelshell.java:44) @ com.jcraft.jsch.channel.connect(channel.java:152) @ com.apple.mailmove.ssh.executesecureshellcommand.runcommand(executesecureshellcommand.java:90) @ com.apple.mailmove.ssh.executesecureshellcommand.main(executesecureshellcommand.java:160) 

and here runcommad code:

//find below method  public void runcommand(string command)   {   try{     = new bytearrayinputstream(command.getbytes());    channel.setinputstream(is);     channel.setoutputstream(baos);     channel.connect(15 * 1000);     // wait 3 seconds demo complete (ie: output streamed us).     thread.sleep(3*1000);     (int timeout = 200000; timeout > 0; timeout--)      {       if(baos.size() != 0)       {         system.out.println(baos.tostring());         break;       }       else       {         system.out.println("no output!!!!");         thread.sleep(5000); // wait bit try again       }     }   }   catch(exception e)   {      e.printstacktrace();   }  } 

checked connection status

channel.isconnected  

method before channel.conenct(15*1000) called , displayed true. once channel.conenct(15*1000) called channel connection status returns false.

i not able understand why channel gets disconnected when channel.connect(15*1000) called second time. there other way execute commands 1 one output of previous command , execute second command?

for running 1 or more commands via ssh, recommend use exec channel jsch provides. full example, see this page.

you'll have change code create new channel each command want run:

public void runcommand(string command) {     channelexec channel = (channelexec)session.openchannel("exec");     channel.setcommand(command);      try (inputstream stdout = channel.getinputstream();           inputstream stderr = channel.geterrstream()) {         channel.connect(timeout);         // read stdout , stderr     }      channel.disconnect(); } 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - .htaccess mod_rewrite for dynamic url which has domain names -

Website Login Issue developed in magento -