I am working on running telnet
command on SSH shell session, for obtaining it I used JSch following the official example.
I wrote my own code following also this example on StackOverflow
this is my code:
package Utility;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
public class JavaTelnet {
public static void main(String[] arg) {
try {
System.out.println(telnetConnection(USER_ID,PASSWORD,REMOTE_HOST));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String telnetConnection(String user, String password, String host) throws JSchException, Exception {
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
// It must not be recommended, but if you want to skip host-key check,
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
//session.connect(30000); // making a connection with timeout.
Channel channel=session.openChannel("shell");
channel.connect();
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(dataIn));
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
dataOut.writeBytes("telnet localhost 4242\r\n");
/*
* telnet COMMANDS here
*/
dataOut.writeBytes("exit\r\n");
dataOut.writeBytes("logout\r\n");
dataOut.flush();
String line = reader.readLine();
String result = line +"\n";
while ((line= reader.readLine())!=null){
result += line +"\n";
}
dataIn.close();
dataOut.close();
System.out.println("disconnecting....");
channel.disconnect();
session.disconnect();
return "done";
}
}
It look like good but the strange thing is that it is working only in debug mode. If I run it the program don't reach his end. I think it is locking on the while loop but I don't understand why. Without the while loop the code reach his end but don't execute any shell command.
I am using Netbeans as IDE
Can you help me to find the problem?!