Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send keyboard function keys to SSH server from java code

There is a menu item that gets displayed on the console after the connection of the session. And that menu items have command with F1, F2, F3

String host="myhost.abc.123";
String user="devuser";
String password="dev1234";

Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = null;
ChannelShell channel = null;

session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");

channel = (ChannelShell) session.openChannel("shell");
OutputStream out_s = channel.getOutputStream();
channel.connect();

I want to send the F2 - function key as a hardcoded escape sequence or from the keyboard, to server. Tried below options but I am not getting the next response/output

/* --- code for printing the menu item on the console/screen ---
MENU ITEMS GET PRINTED ON THE CONSOLE
F1 - ADD   F2 - UPDATE   F3 - DELETE      
*/

//Try 1. F2 - ESC[OQ 
out_s.write("\033[OQ".getBytes()); // may require \n or \r to enter the cmd
out_s.flush();

//Try 2. F2 - ESC[12~ 
out_s.write("\033[12~".getBytes()); // may require \n or \r to enter the cmd
out_s.flush();

//Try 3. F2 - \E[12~ 
out_s.write("\\E[12~".getBytes());
out_s.flush();

//Try 4. F2 - 0x71 
out_s.write((byte)0x71); // may require \n or \r to enter the cmd
out_s.flush();

//Try 5. F2 - \ESC[OQ
out_s.write("\\ESC[OQ".getBytes());
out_s.flush();
like image 298
Mohit Avatar asked Nov 23 '25 07:11

Mohit


1 Answers

This worked for me:

out.write("\u001b[12~".getBytes());
out.flush();

On the server I tested by:

read -n 5 key

This reads 5 bytes from standard input without waiting for a return key. Of course, this is only for test. You can do your own processing on the server side.

How to find out what is being sent by a specific key (in bash):

read key

Then type (for example) the F2 key. The terminal should show something like this:

^[[12~

If not, try this command to show the bytes sent to the terminal:

echo $key | cat -t

In the output ^[ stands for the (non printable) escape character. The other characters stand for themselves.

like image 76
Donat Avatar answered Nov 24 '25 21:11

Donat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!