Using following code snippet, we can execute shell script hosted in remote Unix machine. To compile following program, we need to add Jsch JAR file available from http://www.jcraft.com/jsch/.
Code snippet:
package client;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class execJSch {
public execJSch() {
super();
}
/**
* Comments by lkakarla
* Following code snippet calls shell script resides in remote Unix machine.
* Note: For reusability, set host pwd command variables as parameters
* @param args
*/
public static void main(String[] args) {
try {
JSch jsch = new JSch();
String host = "user@host";
String pwd = "password";
String command = "/usr/bin/lkakarla/TestSH.sh";
String user = host.substring(0, host.indexOf('@'));
host = host.substring(host.indexOf('@') + 1);
Session sessionJSH = jsch.getSession(user, host, 22);
sessionJSH.setPassword(pwd);
java.util.Hashtable configJSH = new java.util.Hashtable();
configJSH.put("StrictHostKeyChecking", "no");
sessionJSH.setConfig(configJSH);
sessionJSH.connect();
Channel channel = sessionJSH.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.connect();
channel.disconnect();
sessionJSH.disconnect();
}
catch (Exception e) {
System.out.println(e);
}
}
}
This is a cool post
ReplyDeleteIts not running. Not giving any error, But shell script is not executed. Please say how to know about error.
ReplyDeleteHey how do we execute multiple commands.?
ReplyDeleteconnection time out
ReplyDeleteits not executing,. java code is working without error but there shell is not running /.....facing same issue like above Mukesh said..help me to solve this issue na
ReplyDelete