|
http://www.jcraft.com/jsch/
Sample code to execute remote script:
import com.jcraft.jsch.*;
import java.io.InputStream;
...
// Configure JSch:
JSch.setConfig("StrictHostKeyChecking", "no");
// Environment:
final String user = "subwiz";
final String host = "localhost";
final String password = "password";
JSch jsch=new JSch();
// jsch.addIdentity("/path/to/mypem.pem");
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.connect();
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setPty(true);
((ChannelExec)channel).setCommand("cat /etc/passwd; exit;");
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
StringBuilder sb = new StringBuilder();
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
String str = new String(tmp, 0, i);
sb.append(str);
System.out.print(str);
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
// return sb.toString();
|
|