i had to execute few linux commands remotely on some systems in my application. so i connected
to that system on ssh port using library jsch and then executed those commands. i have written a sample program for you. Infact it is modified version of the example given on jsch site. That example was using swing a lot i removed it altogether.



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package com.bhagat;

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.UserInfo;
import com.jcraft.jsch.Session;


public class RemoteExec {

public static void main(String[] arg){
try{
JSch jsch=new JSch(); 
Session session=jsch.getSession("username", "ipaddress", 22);

UserInfo ui=new MyUserInfo("password");
session.setUserInfo(ui);
session.connect();
String command="ps \nls";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
String result=""; 
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0 break="" div="">
result+=new String(tmp, 0, i);
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
}
System.out.println("reutls++++++++++++++++++++++++++++++"+result);
channel.disconnect();
session.disconnect();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo{
public String getPassword(){ return passwd; }
public boolean promptYesNo(String str){
return true;
}
public MyUserInfo(String pwd)
{
this.passwd=pwd;
}
String passwd;
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return false; }
public boolean promptPassword(String message) {
System.out.println("promptPassword called with message"+message);
return true;
}
public void showMessage(String message) {
//System.out.println("Message"+message);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
0

Add a comment

Blog Archive
About Me
About Me
Loading