I was looking for a solution to take SSH connection followed by Telnet connection to remote system via java. As using telnet connection only I can execute that particular command on remote machine.
After browsing a lot I found this answer "https://stackoverflow.com/questions/27146991/running-telnet-command-on-remote-ssh-session-using-jsch" But after Executing the "telnet localhost 4444" the program executions hangs & never come out from while loop . Because of that I'm not able to execute other commands after taking telnet connection.
My code is :-
public static void main(String[] arg) {
try {
System.out.println(telnetConnection(command, puttyUserName,
puttyPassword, puttyHostName));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String telnetConnection(String command, String user, String password, String host)
throws JSchException, Exception {
JSch jsch = new JSch();
jsch.addIdentity(puttyPublicKey, puttyPassword);
Session session = jsch.getSession(user, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(500);//This timeout is not working as mentioned in the example. Program execution never stops.
Channel channel = session.openChannel("shell");
channel.connect(500);
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(dataIn));
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
System.out.println("Starting telnet connection...");
dataOut.writeBytes("telnet localhost 4444\r\n"); after this no commands executes
dataOut.writeBytes(command + "\r\n");
dataOut.writeBytes("quit\r\n");
// using quit I'm able to exit from telnet session while doing manually via putty as exit doesn't work
dataOut.writeBytes("exit\r\n"); // exit from shell
dataOut.flush();
String line = reader.readLine();
String result = line + "\n";
while (!(line = reader.readLine()).equals("Connection closed by foreign host"))
{
result += line + "\n";
System.out.println("heart beat" + result);
}
System.out.println("after while done");
dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();
System.out.println("done");
return result;
}
}
output//
heart beat telnet localhost 4444
START TRANSLATOR ABCLOC HIGH
quit
exit
[XYZ]$ telnet localhost 4444 Trying x.x.x.1...
Connected to localhost.localdomain (x.x.x.1).
Escape character is '^]'.
Connection to INTERFACE LAYER heart beat telnet localhost 4444
START TRANSLATOR ABCLOC HIGH
quit
exit
[XYZ]$ telnet localhost 4444 Trying x.x.x.1...
Connected to localhost.localdomain (x.x.x.1).
Escape character is '^]'.
Connection to INTERFACE LAYER Type "help" for a list of commands
////after this programs hangs & no actions are performed