使用java在LINUX中执行命令并获取输出 [英] Execute a command in LINUX using java and fetch the output
问题描述
我正在使用Groovy在我的LINUX盒子上执行命令并取回输出,但我无法以某种方式使用 |
管道(我想)或者可能会它不会等待命令完成,什么是错误的,或者我在代码中丢失了什么?
我的调用函数
def test()
{
字符串结果=N
HashMap< ;字符串,字符串> params = IntermediateResults.get(userparams)
Map env = AppContext.get(AppCtxProperties.environmentVariables)
$ b def fClass = new GroovyClassLoader()。parseClass(new File('plugins / infa9 /Infa9CommandExecUtil.groovy'))
List< String> frows = [uname -a,
uname -a | awk'{print\ $ 2}',
uname -a | cut -d''-f 2]
List< String> resultRows = fClass.newInstance()。fetchCommandOutput(params,env,frows)
返回结果
}
Infa9CommandExecUtil.groovy 文件内容更新已添加exitVal println
package infa9
import java.io.BufferedReader;
public class Infa9CommandExecUtil {
StringBuffer result
$ b public Infa9CommandExecUtil(){
result = new StringBuffer()
}
public List< String> fetchCommandOutput(Map< String,String> params,Map env,List< String> rows)
{
List< String> outputRows = new ArrayList< String>()
尝试
{
for(item in rows)
{
String temp = item.toString()
printlnCMD:$ temp
Process proc = Runtime.getRuntime()。exec(temp);
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
result = new StringBuffer()
line = null
$ b $ int exitVal = proc.waitFor()//我是否需要等待线程/进程在这里完成? ((line = br.readLine())!= null)
{
result.append(line + System.getProperty(line.separator))/
/ /维护格式(换行符)
}
String tRes = result
tRes = tRes.trim()
printlnOUTPUT:$ tRes\\\
EXITVAL:$ exitVal
outputRows.add(tRes)
}
}
catch(IOException io){io.printStackTrace();}
catch(InterruptedException ie){ ie.printStackTrace();}
return outputRows
}
}
我的输出 * 更新添加的退出价值 *
CMD: uname -a
OUTPUT:Linux estilo 2.6.18-128.el5#1 SMP Wed Dec 17 11:41:38 EST 2008 x86_64 x86_64 x86_64 GNU / Linux
EXITVAL:0
CMD: uname -a | awk'{print $ 2}'
输出:
EXITVAL:1
CMD:uname -a | cut -d''-f 2
OUTPUT:
EXITVAL:1
更新
注意:我内部使用 sh -c< command> / code>
您无法使用执行管道或重定向String.execute / code>。这在Java中不起作用,所以它在Groovy中无法正常工作......
您可以使用 Process.pipeTo
用Groovy来简化事情:
pre $ proc ='uname -a'.execute()
Process procb ='awk {print \ $ 2}'。execute()
(proca | procb).text
更通用的版本可能是:
String process ='uname -a | awk {print \ $ 2}'
//根据|将字符串拆分为多个部分
//将结果一起输出
处理结果= process.tokenize('|').inject(null){p,c - >
if(p)
p | c.execute()
else
c.execute()
}
//输出输出和错误流
result.waitForProcessOutput(System.out,System .out)
I am using Groovy to execute commands on my LINUX box and get back the output, but I am not able to use |
pipes somehow (i think) or may be it is not waiting for the command to finish, what is wrong, or what am i missing in my code?
My Calling function
def test()
{
String result="N"
HashMap<String,String> params = IntermediateResults.get("userparams")
Map env=AppContext.get(AppCtxProperties.environmentVariables)
def fClass = new GroovyClassLoader().parseClass( new File( 'plugins/infa9/Infa9CommandExecUtil.groovy' ) )
List<String> frows=["uname -a",
"uname -a | awk '{print\$2}'",
"uname -a | cut -d ' ' -f 2"]
List<String> resultRows = fClass.newInstance().fetchCommandOutput( params, env, frows )
return result
}
Infa9CommandExecUtil.groovy file content Update added exitVal println
package infa9
import java.io.BufferedReader;
public class Infa9CommandExecUtil {
StringBuffer result
public Infa9CommandExecUtil() {
result = new StringBuffer()
}
public List<String> fetchCommandOutput( Map<String,String> params, Map env, List<String> rows )
{
List<String> outputRows = new ArrayList<String>()
try
{
for(item in rows)
{
String temp=item.toString()
println "CMD:$temp"
Process proc = Runtime.getRuntime().exec(temp);
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
result = new StringBuffer()
line=null
int exitVal = proc.waitFor() //do I need to wait for the thread/process to finish here?
while ((line = br.readLine()) != null)
{
result.append(line+System.getProperty("line.separator")) //to maintain the format (newlines)
}
String tRes=result
tRes=tRes.trim()
println "OUTPUT:$tRes\nEXITVAL:$exitVal"
outputRows.add(tRes)
}
}
catch (IOException io) { io.printStackTrace();}
catch (InterruptedException ie) {ie.printStackTrace();}
return outputRows
}
}
My Output *Update added exitVal value*
CMD:uname -a
OUTPUT:Linux estilo 2.6.18-128.el5 #1 SMP Wed Dec 17 11:41:38 EST 2008 x86_64 x86_64 x86_64 GNU/Linux
EXITVAL:0
CMD:uname -a | awk '{print$2}'
OUTPUT:
EXITVAL:1
CMD:uname -a | cut -d ' ' -f 2
OUTPUT:
EXITVAL:1
Update
Note: I am internally using sh -c <command>
You cannot do pipes or redirects using String.execute()
. This doesn't work in Java, so it doesn't work in Groovy either...
You can use Process.pipeTo
with Groovy to simplify things:
Process proca = 'uname -a'.execute()
Process procb = 'awk {print\$2}'.execute()
(proca | procb).text
A more generic version could be:
String process = 'uname -a | awk {print\$2}'
// Split the string into sections based on |
// And pipe the results together
Process result = process.tokenize( '|' ).inject( null ) { p, c ->
if( p )
p | c.execute()
else
c.execute()
}
// Print out the output and error streams
result.waitForProcessOutput( System.out, System.out )
这篇关于使用java在LINUX中执行命令并获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!