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-