我正在嘗試使用帶有 Jsch 的 linux 命令處理確認問題(y/n)。我能夠在錯誤流中得到問題。但是在輸出流中寫一個'y'作為答案后,命令沒有得到它。我嘗試使用的 SAMPLE 命令是 'rm -i file1.txt' 并且在寫入 'y' 后文件沒有被刪除。在確認應該從輸入流中讀取的“y”后,我的目標命令也會返回結果。回聲 y | 使用 target 命令對我來說不是一個選項。 java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig(config); session.connect(); System.out.println("Connected"); System.out.println(command); ChannelExec channel = (ChannelExec) session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream in = channel.getInputStream(); OutputStream outChannel = channel.getOutputStream(); InputStream errStream = channel.getErrStream(); PrintWriter writer = new PrintWriter(outChannel); channel.connect(); byte[] errTmp = new byte[1024]; while (errStream.available() > 0) { int i = errStream.read(errTmp, 0, 1024); if (i < 0) break; sysout = new String(errTmp, 0, i); System.out.println("Error Line:"+sysout); if(sysout.toLowerCase().contains("remove regular file")) { writer.println("y"); // Works till here but not deleting file } } byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; sysout = new String(tmp, 0, i); System.out.println(sysout); }
1 回答

www說
TA貢獻1775條經驗 獲得超8個贊
PrintWriter
s 除非被要求,否則不會自動刷新,所以我相信您在沒有實際發送y
.
您可以創建一個在使用構造函數調用PrintWriter
時將自動刷新的。println
PrintWriter(OutputStream out, boolean autoflush)
我還認為您應該避免在等待結果的循環中調用channel.disconnect()
,while (true)
因為您可以確定一旦關閉通道就不會得到結果。
添加回答
舉報
0/150
提交
取消