This post shows a simple java class which allows you to run unix commands on a remote server. Java Secure Chanel (JSch) library is used to run the commands. JSch is used in Ant and Eclipse. The only third party library required is jsch-0.x.x.jar.
package com.demo.jsch;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
public class ShellExample {
public static void main(String[] args) {
String user = "username";
String host = "servername";
JSch jsch = new JSch();
try {
Session session = jsch.getSession(user, host, 22);
UserInfo userInfo = new MyUserInfo();
session.setUserInfo(userInfo);
session.connect(30000);
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect(3 * 1000);
} catch (JSchException e) {
e.printStackTrace();
}
}
public static class MyUserInfo implements UserInfo {
public String getPassword() {
return "password";
}
public String getPassphrase() {
return "";
}
public boolean promptPassword(String arg0) {
return true;
}
public boolean promptPassphrase(String arg0) {
return true;
}
public boolean promptYesNo(String arg0) {
return true;
}
public void showMessage(String arg0) {
}
}
}
April 11, 2007 at 1:25 pm |
But where will you put the command you want to run ? After the channel.connect() ?
Where will you get the result ?
April 29, 2009 at 11:46 am |
What is the content of UserInfo class ?