Created
December 12, 2012 13:46
-
-
Save anonymous/4267827 to your computer and use it in GitHub Desktop.
a sample code for http://stackoverflow.com/questions/13804001/java-ganymed-ssh-hangs-while-reading-from-buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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