Execute a list of commands from an ArrayList using JSch exec in Java -


using jsch "exec" channel, connect remote server , execute command. can't execute list of commands stored in arraylist. use loop pass each element .setcommand(elem); odd reason, last command gets executed.

arraylist<string> lists = new arraylist<string>(); lists.add("hostname"); lists.add("df -l"); channel channel=session.openchannel("exec");  (string elem : lists){     ((channelexec)channel).setcommand(elem); } 

full code

public class exec{   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 session=jsch.getsession(user, host, 22);         userinfo ui=new myuserinfo();       session.setuserinfo(ui);       session.connect();        arraylist<string> lists = new arraylist<string>();         lists.add("hostname");         lists.add("df -l");       channel channel=session.openchannel("exec");        (string elem : lists){           ((channelexec)channel).setcommand(elem);       }        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()){           if(in.available()>0) continue;            system.out.println("exit-status: "+channel.getexitstatus());           break;         }         try{thread.sleep(1000);}catch(exception ee){}       }       channel.disconnect();       session.disconnect();     }     catch(exception e){       system.out.println(e);     }   }    public static class myuserinfo implements userinfo, uikeyboardinteractive{     public string getpassword(){ return passwd; }     public boolean promptyesno(string str){       object[] options={ "yes", "no" };       int foo=joptionpane.showoptiondialog(null,               str,              "warning",               joptionpane.default_option,               joptionpane.warning_message,              null, options, options[0]);        return foo==0;     }      string passwd;     jtextfield passwordfield=(jtextfield)new jpasswordfield(20);      public string getpassphrase(){ return null; }     public boolean promptpassphrase(string message){ return true; }     public boolean promptpassword(string message){       object[] ob={passwordfield};        int result=         joptionpane.showconfirmdialog(null, ob, message,                                       joptionpane.ok_cancel_option);       if(result==joptionpane.ok_option){         passwd=passwordfield.gettext();         return true;       }       else{          return false;        }     }     public void showmessage(string message){       joptionpane.showmessagedialog(null, message);     }     final gridbagconstraints gbc =        new gridbagconstraints(0,0,1,1,1,1,                              gridbagconstraints.northwest,                              gridbagconstraints.none,                              new insets(0,0,0,0),0,0);     private container panel;     public string[] promptkeyboardinteractive(string destination,                                               string name,                                               string instruction,                                               string[] prompt,                                               boolean[] echo){       panel = new jpanel();       panel.setlayout(new gridbaglayout());        gbc.weightx = 1.0;       gbc.gridwidth = gridbagconstraints.remainder;       gbc.gridx = 0;       panel.add(new jlabel(instruction), gbc);       gbc.gridy++;        gbc.gridwidth = gridbagconstraints.relative;        jtextfield[] texts=new jtextfield[prompt.length];       for(int i=0; i<prompt.length; i++){         gbc.fill = gridbagconstraints.none;         gbc.gridx = 0;         gbc.weightx = 1;         panel.add(new jlabel(prompt[i]),gbc);          gbc.gridx = 1;         gbc.fill = gridbagconstraints.horizontal;         gbc.weighty = 1;         if(echo[i]){           texts[i]=new jtextfield(20);         }         else{           texts[i]=new jpasswordfield(20);         }         panel.add(texts[i], gbc);         gbc.gridy++;       }        if(joptionpane.showconfirmdialog(null, panel,                                         destination+": "+name,                                        joptionpane.ok_cancel_option,                                        joptionpane.question_message)          ==joptionpane.ok_option){         string[] response=new string[prompt.length];         for(int i=0; i<prompt.length; i++){           response[i]=texts[i].gettext();         }         return response;       }       else{         return null;  // cancel       }     }   } } 

you cannot call setcommand multiple times. "exec" channel can run single "command" only.

but on systems/shells, "command" can include multiple commands.

a syntax depend on system/shell. semicolons work usually:

((channelexec)channel).setcommand("hostname ; df -l"); 

some servers/shells allow newline.

((channelexec)channel).setcommand("hostname\ndf -l"); 

on *nix servers, can use && make following commands executed when previous commands succeeded:

((channelexec)channel).setcommand("hostname && df -l"); 

another option open new channel each command. note can have multiple channels on single ssh session. not have reconnect each channel/command.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

python - malformed header from script index.py Bad header -