Java通过JSch运行远程shell脚本时如何提供交互选择输入
解决方法
核心原理是你当前只读取了远端脚本的输出流,没有获取远端进程的标准输入流来写入交互内容,按下面的步骤调整代码即可:
代码修改点
- 修正配置加载顺序:你当前的
StrictHostKeyChecking配置写在了session.connect()之后,不会生效,要移到连接之前 - 从
ChannelExec获取可写入的输出流,对应远端进程的标准输入,你往这个流里写的内容会当做用户输入传给脚本 - 按交互顺序写入对应的内容,每次写完要执行
flush确保内容立即发送,注意末尾加换行符\n模拟回车确认
完整可运行示例代码(以选1、输入路径/data/myproject为例)
JSch jsch = new JSch(); String command = "/tmp/myscript.sh"; Session session = jsch.getSession(user, host, 22); // 配置要放在connect之前 java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec)channel).setCommand(command); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in = channel.getInputStream(); // 获取远端标准输入对应的输出流 OutputStream out = channel.getOutputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) { break; } String output = new String(tmp, 0, i); System.out.print(output); // 检测输出内容,匹配到对应提示就发输入 if (output.contains("Please select from below menu options")) { // 输入选项1加回车 out.write("1\n".getBytes()); out.flush(); } if (output.contains("Please enter the path where you want to create a directory")) { // 输入路径加回车 out.write("/data/myproject\n".getBytes()); out.flush(); // 所有输入发完可以关闭输入流,避免脚本一直等输入 out.close(); } } if (channel.isClosed()) { if (channel.getExitStatus() == 0) { System.out.println("Command executed successfully."); } break; } // 加个小延迟避免空转占用CPU Thread.sleep(100); } channel.disconnect(); session.disconnect();
注意事项
- 如果脚本交互步骤多,建议封装成匹配关键词再发输入的通用逻辑,不要硬编码等待时间,避免网络波动导致输入发送时机不对
- 所有交互内容发送完成后建议关闭输入流,告诉远端进程没有更多输入了,避免脚本卡住等待
- 如果是非常复杂的终端交互场景,可以改用
ChannelShell通道,模拟完整终端行为,适配需要终端环境的脚本
内容的提问来源于stack exchange,提问作者Sh87
相关产品推荐
相关产品推荐

