当我使用JSch运行命令时删除不需要的字符

jsch = new JSch(); session = jsch.getSession(userName, ip, 22); session.setPassword(passWord); session.connect(); channel = session.openChannel("shell"); expect = new Expect(channel.getInputStream(), channel.getOutputStream()); ((ChannelShell) channel).setPtyType("dumb"); channel.connect(); System.out.println("After channel and expect"); if (expect.expect("#") > -1) { output = "Connected"; } else { output = "Unexpected Prompt"; System.out.println("Unexpected Prompt"); } expect.send("top" + "\n"); Thread.sleep(3000); System.out.println("inside top"); OutputStream out = channel.getOutputStream(); out.write(3); // send CTRL-C out.flush(); System.out.println("exit1"); if (expect.expect("$") > -1) { System.out.println("finding $"); contt = (expect.before); if (contt != null && contt != "") { output=StringUtils.replace(contt,"\"",""); System.out.println("afterline"+output); } else { contt="Error in Top Check"; System.out.println("Error in Top check"); } } else { System.out.println("oit"); } 

当我运行此代码时,我正在输出

 [H[J[mtop - 05:54:39 up 53 days, 15:21, 22 users, load average: 0.44, 0.80, 0.76[m[K Tasks:[m[m 443 [mtotal,[m[m 1 [mrunning,[m[m 442 [msleeping,[m[m 0 [mstopped,[m[m 0 [mzombie[m[K Cpu(s):[m[m 2.8%[mus,[m[m 0.8%[msy,[m[m 0.1%[mni,[m[m 95.9%[mid,[m[m 0.3%[mwa,[m 

像这些。 我随身携带不需要的角色。 我该如何删除它们?

这些是ANSI转义码 ,通常由终端客户端解释为非常打印输出。

你得到这些,因为你默认为JSch“shell”通道请求会话的伪终端 。 一般来说,使用“shell”通道进行自动化是一个坏主意。

但是如果由于某种原因你真的必须通过调用setPty禁用伪终端:

 channel.setPty(false); 

但在99%的情况下,这是一个坏主意。 试图模拟人类是容易出错的。 命令的人机交互function往往会改变(得到改进),反过来会在服务器更新时破坏您的代码。

你最好问一个关于你最终目标的新问题(你想用什么top的?),因为你可能走错了路。


相关问题:

  • 从JSch中的命令输出中删除shell东西(如提示)
  • 有没有一种简单的方法来摆脱使用Python的Paramiko库进行SSH并从远程计算机的CLI获取输出时出现的垃圾值?