Skip to content

Instantly share code, notes, and snippets.

Created December 12, 2012 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4267827 to your computer and use it in GitHub Desktop.
Save anonymous/4267827 to your computer and use it in GitHub Desktop.
import com.jcraft.jsch.*;
import java.io.*;
public class Exec{
public static void main(String[] arg){
try{
JSch jsch=new JSch();
String host="127.0.0.1";
String user="YYYYYYYYY";
String passwd="XXXXXXXXX";
Session session=jsch.getSession(user, host, 22);
session.setPassword(passwd);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command="/bin/bash";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
((ChannelExec)channel).setPty(true);
InputStream in=channel.getInputStream();
OutputStream out=channel.getOutputStream();
channel.connect();
out.write("echo 'test'; exit\n".getBytes());
out.flush();
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){}
}
System.out.println("finished");
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment