如何从Java代码向SSH服务器发送键盘功能键

问题描述

连接会话后,控制台上会显示一个菜单项。并且这些菜单项具有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();

我要发送F2-功能键作为硬编码转义序列,或者 从键盘到服务器。 尝试了以下选项,但没有得到下一个响应/输出

/* --- 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();

解决方法

这对我有用:

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

在我测试过的服务器上:

read -n 5 key

这将从标准输入中读取5个字节,而无需等待返回键。当然,这仅用于测试。您可以在服务器端进行自己的处理。

如何找出特定密钥(以bash格式)发送的内容:

read key

然后键入(例如)F2键。终端应显示以下内容:

^[[12~

如果没有,请尝试以下命令以显示发送到终端的字节:

echo $key | cat -t

在输出^[中代表(不可打印的)转义字符。其他角色代表自己。