Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

connecting to unix using JSch

807580Jan 8 2008 — edited Aug 12 2010
Hi,

I need to connect and execute a series of command using JCraft's, Jsch APIs. Please find the below code (Modified from http://www.jcraft.com/jsch/examples/Exec.java). first command is executing but the second onwards is not working.
Your replay appriciated.
public class Exec{
	public static Channel channel = null;
	public static Session session = null;
  public static void main(String[] arg){
    try{
      JSch jsch=new JSch();  
      String host=null;
      if(arg.length>0){
        host=arg[0];
      }
      else{
        host=JOptionPane.showInputDialog("Enter username@hostname",
                                         System.getProperty("user.name")+
                                         "@localhost"); 
      }
      String user=host.substring(0, host.indexOf('@'));
      host=host.substring(host.indexOf('@')+1);
      session=jsch.getSession(user, host, 22);
      UserInfo ui=new MyUserInfo();
      session.setUserInfo(ui);
      session.connect(3000);

      String command="";
      String cmdArray[] = {"pwd","pwd","sudo su - dev","ssh myservername","ls -ltr /apps/sunone"};
      channel=session.openChannel("exec");
      channel.setInputStream(null);
      
      for (int c=0;c<cmdArray.length;c++){
    	  command = cmdArray[c];
      ((ChannelExec)channel).setCommand(command);
      System.out.println("Command : "+command+" "+c);
	  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){}
      }
      }
    }
    
    catch(Exception e){
      System.out.println(e.getMessage());
    }
    finally{
    	channel.disconnect();
    	session.disconnect();
    }
  }
Regards,
Sreejith-
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 9 2010
Added on Jan 8 2008
2 comments
928 views