简体   繁体   English

如何在Java中运行Linux命令时只显示结果?

[英]How to show only the result when running Linux command in Java?

I am using JSch to run some command in remote Linux box. 我正在使用JSch在远程Linux机器中运行一些命令。

session = jsch.getSession(user, "host", 1222);
...
Channel shellChannel = session.openChannel("shell");
OutputStream ops = shellChannel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);

ps.println("pwd");
InputStream in = shellChannel.getInputStream();
...
//print the char stream from 'in' using something similar to 
//http://stackoverflow.com/questions/9126142/output-the-result-of-a-bash-script#

However, the printout of the result from inputStream contains everything, including user prompt, my original command ( pwd in this case), and the result /u02/app2/bbisit : 但是, inputStream的结果打印输出包含所有内容,包括用户提示,原始命令(本例中为pwd )和结果/u02/app2/bbisit

bbisit@sdvdbres016$ 
bbisit@sdvdbres016$ pwd
/u02/app2/bbisit

But all I really want is the real output of the command, ie /u02/app2/bbisit . 但我真正想要的只是命令的实际输出,即/u02/app2/bbisit

Is there a way to get only the actual result of the command, but not the other garbage. 有没有办法只获得命令的实际结果,而不是其他垃圾。

Use the "exec" channel, not the "shell" channel. 使用“exec”通道,而不是“shell”通道。

The "exec" channel is intended for automating command execution. “exec”通道用于自动执行命令。 The "shell" channel is intended for implementing an interactive shell. “shell”通道用于实现交互式shell。

See http://www.jcraft.com/jsch/examples/Exec.java.html 请参阅http://www.jcraft.com/jsch/examples/Exec.java.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM