代码方法如下:
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();
ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);
//There should really be a timeout here.
if (0 != process.waitFor())
return null;
return output;
} catch (Exception e) {
// 处理异常
}
}
Ⅱ 如何用java调用linux shell命令
**
* 运行shell脚本
* @param shell 需要运行的shell脚本
*/
public static void execShell(String shell){
try {
Runtime rt = Runtime.getRuntime();
rt.exec(shell);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 运行shell
*
* @param shStr
* 需要执行的shell
* @return
* @throws IOException
*/
public static List runShell(String shStr) throws Exception {
List<String> strList = new ArrayList();
Process process;
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null);
InputStreamReader ir = new InputStreamReader(process
.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
process.waitFor();
while ((line = input.readLine()) != null){
strList.add(line);
}
return strList;
}
Ⅲ 如何在java程序中调用linux命令或者shell脚本
java程序是提供了这个一方法,Processpro=Runtime.getRuntime().exec(cmds);
但是一般来说,尽量去用一些其他脚本(lua,shell,python)去执行一系列linux命令比较灵活, 而且耗费资源少。但是Runtime.getRuntime().exec()这种调用方式在java虚拟机中是十分消耗资源的,即使命令可以很快的执行完毕,频繁的调用时创建进程消耗十分可观。
java虚拟机执行这个命令的过程是,首先克隆一条和当前虚拟机拥有一样环境变量的进程,再用这个新的进程执行外部命令,最后退出这个进程。频繁的创建对CPU和内存的消耗很大。
下面是一个调用linux命令的例子:
publicclassTest{
publicstaticvoidmain(String[]args)throwsException{
String[]cmds={"/bin/sh","-c","ps-ef|grepjava"};
Processpro=Runtime.getRuntime().exec(cmds);
pro.waitFor();//阻塞,直到上述命令执行完
InputStreamin=pro.getInputStream();
BufferedReaderread=newBufferedReader(newInputStreamReader(in));
Stringline=null;
while((line=read.readLine())!=null){
System.out.println(line);
}
}
}
Ⅳ 如何用java调用linux shell命令
用java调用linux shell命令:
String shpath="/test/test.sh"; //程序路径
Process process =null;
String command1 = “chmod 777 ” + shpath;
process = Runtime.getRuntime().exec(command1);
process.waitFor();
String var="201102"; //参数
String command2 = “/bin/sh ” + shpath + ” ” + var;
Runtime.getRuntime().exec(command2).waitFor();
Ⅳ linux下java执行shell命令,该怎么解决
package com.chinasoft;
import java.io.IOException;
public class LiunxEXEjava {
public static void main(String[] args) {
Process process=null;
try {
//path 程序路径
//exec(shell 命令)
process= Runtime.getRuntime().exec("chmod 777 path");
process.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
process这个类是一个抽象类,封装了一个进程(你在调用linux的命令或者shell脚本就是为了执行一个在linux下执行的程序,所以应该使用process类)。
process类提供了执行从进程输入,执行输出到进程,等待进程完成,检查进程的推出状态,以及shut down掉进程。
至于详细的process类的介绍放在以后介绍。
另外还要注意一个类:Runtime类,Runtime类是一个与JVM运行时环境有关的类,这个类是Singleton的。
这里用到的Runtime.getRuntime()方法是取得当前JVM的运行环境,也是java中唯一可以得到运行环境的方法。(另外,Runtime的大部分方法都是实例方法,也就是说每次运行调用的时候都需要调用到getRuntime方法)
下面说说Runtime的exec()方法,这里要注意的有一点,就是public Process exec(String [] cmdArray, String [] envp);这个方法中cmdArray是一个执行的命令和参数的字符串数组,数组的第一个元素是要执行的命令往后依次都是命令的参数,envp感觉应该和C中的execve中的环境变量是一样的,envp中使用的是name=value的方式。
Ⅵ Java在linux上调用shell脚本
用.sh 脚本call 第一不会超时的,第二只要你后台call进去了,就算前台超时了 后台还是一直在执行
建议把你的java program打包成jar 直接call 你的jar 包
列子
#!/bin/bash
java -cp ./config:/activation.jar:/axis.jar:test.jar com.Test.run param1,param2
-cp 是你文件 path
config 是你配置文件放置位置, jar 和 sh script 同一级目录(可以根据你具体自己修改)
最后只是你需要run 的class了, 在class 里面去call 你对应的procere
Ⅶ 使用java连接linux,执行shell命令返回值有乱码,怎么解决
packagecom.pasier.xxx.util;
importjava.io.IOException;
importjava.io.InputStream;
importjava.nio.charset.Charset;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importch.ethz.ssh2.ChannelCondition;
importch.ethz.ssh2.Connection;
importch.ethz.ssh2.Session;
importch.ethz.ssh2.StreamGobbler;
publicclassRmtShellExecutor{
privatestaticfinalLoggerLOG=LoggerFactory.getLogger(RmtShellExecutor.class);
privateConnectionconn;
privateStringip;
privateStringusr;
privateStringpsword;
privateStringcharset=Charset.defaultCharset().toString();
privatestaticfinalintTIME_OUT=1000*5*60;
publicRmtShellExecutor(Stringip,Stringusr,Stringps){
this.ip=ip;
this.usr=usr;
this.psword=ps;
}
privatebooleanlogin()throwsIOException{
conn=newConnection(ip);
conn.connect();
returnconn.authenticateWithPassword(usr,psword);
}
publicStringexec(Stringcmds)throwsIOException{
InputStreamstdOut=null;
InputStreamstdErr=null;
StringoutStr="";
StringoutErr="";
intret=-1;
try{
if(login()){
Sessionsession=conn.openSession();
session.execCommand(cmds);
stdOut=newStreamGobbler(session.getStdout());
outStr=processStream(stdOut,charset);
LOG.info("caijl:[INFO]outStr="+outStr);
stdErr=newStreamGobbler(session.getStderr());
outErr=processStream(stdErr,charset);
LOG.info("caijl:[INFO]outErr="+outErr);
session.waitForCondition(ChannelCondition.EXIT_STATUS,TIME_OUT);
ret=session.getExitStatus();
}else{
LOG.error("caijl:[INFO]ssh2loginfailure:"+ip);
thrownewIOException("SSH2_ERR");
}
}finally{
if(conn!=null){
conn.close();
}
if(stdOut!=null)
stdOut.close();
if(stdErr!=null)
stdErr.close();
}
returnoutStr;
}
privateStringprocessStream(InputStreamin,Stringcharset)throwsIOException{
byte[]buf=newbyte[1024];
StringBuildersb=newStringBuilder();
while(in.read(buf)!=-1){
sb.append(newString(buf,charset));
}
returnsb.toString();
}
publicstaticvoidmain(String[]args){
Stringusr="root";
Stringpassword="12345";
StringserverIP="11.22.33.xx";
StringshPath="/root/ab.sh";
RmtShellExecutorexe=newRmtShellExecutor(serverIP,usr,password);
StringoutInf;
try{
outInf=exe.exec("sh"+shPath+"xn");
System.out.println("outInf="+outInf);
}catch(IOExceptione){
e.printStackTrace();
}
}
}
Ⅷ java怎么执行shell脚本
如果shell脚本和java程序运行在不同的服务器上,可以使用远程执行Linux命令执行包,使用ssh2协议连接远程服务器,并发送执行命令就行了,ganymed.ssh2相关mave配置如下,你可以自己网络搜索相关资料。
如果shell脚本和java程序在同一台服务器上,
这里不得不提到java的process类了。
process这个类是一个抽象类,封装了一个进程(你在调用linux的命令或者shell脚本就是为了执行一个在linux下执行的程序,所以应该使用process类)。
process类提供了执行从进程输入,执行输出到进程,等待进程完成,检查进程的推出状态,以及shut down掉进程。
<dependency>
<groupId>com.ganymed.ssh2</groupId>
<artifactId>ganymed-ssh2-build</artifactId>
<version>210</version>
</dependency>
本地执行命令代码如下:
Stringshpath="/test/test.sh";//程序路径
Processprocess=null;
Stringcommand1=“chmod777”+shpath;
process=Runtime.getRuntime().exec(command1);
process.waitFor();