我正在嘗試使用帶有 Jsch 的 linux 命令處理確認(rèn)問題(y/n)。我能夠在錯(cuò)誤流中得到問題。但是在輸出流中寫一個(gè)'y'作為答案后,命令沒有得到它。我嘗試使用的 SAMPLE 命令是 'rm -i file1.txt' 并且在寫入 'y' 后文件沒有被刪除。在確認(rèn)應(yīng)該從輸入流中讀取的“y”后,我的目標(biāo)命令也會(huì)返回結(jié)果?;芈?y | 使用 target 命令對(duì)我來說不是一個(gè)選項(xiàng)。 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貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
PrintWriter
s 除非被要求,否則不會(huì)自動(dòng)刷新,所以我相信您在沒有實(shí)際發(fā)送y
.
您可以創(chuàng)建一個(gè)在使用構(gòu)造函數(shù)調(diào)用PrintWriter
時(shí)將自動(dòng)刷新的。println
PrintWriter(OutputStream out, boolean autoflush)
我還認(rèn)為您應(yīng)該避免在等待結(jié)果的循環(huán)中調(diào)用channel.disconnect()
,while (true)
因?yàn)槟梢源_定一旦關(guān)閉通道就不會(huì)得到結(jié)果。
添加回答
舉報(bào)
0/150
提交
取消