導航:首頁 > 編程語言 > java調用shell返回

java調用shell返回

發布時間:2022-06-12 17:44:15

A. java執行帶參數的shell腳本並返回值

文件名確實不對
.sh文件才是linux下的批處理文件,它不認bat的
另外要保證.sh中調用的其他函數在當前目錄下能正常運行

B. 如何在java程序中調用linux命令或者shell腳本

publicstaticStringexecShell(StringshellString){
System.out.println("將要執行的shell語句是:"+shellString);
StringisOK="ok";
try{
Processprocess=Runtime.getRuntime().exec(shellString);

BufferedReaderinput=newBufferedReader(newInputStreamReader(process.getInputStream()));
Stringline="";
while((line=input.readLine())!=null){
System.out.println(line);
}
input.close();
intexitValue=process.waitFor();
if(0!=exitValue){
isOK="no";
System.err.println("callshellfailed.errorcodeis:"+exitValue);
}
}catch(Throwablee){
e.printStackTrace();
}

returnisOK;
}

這是我在java中用過的一個調用shell的函數,你可以試試;執行成功返回ok,執行失敗返回no

C. java 調用 shell 腳本

在寫程序時,有時需要在java程序中調用shell腳本,可以通過Runtime的exec方法來調用shell程序,運行腳本。每個Java 應用程序都有一個Runtime 類實例,使應用程序能夠與其運行的環境相連接。通過Runtime對象可以返回運行環境的情況,包括CPU數,虛擬機內存大小等,並能夠通過exec方法調用執行命令。可以通過getRuntime 方法獲取當前Runtime實例。 public boolean ExeShell(){ Runtime rt = Runtime.getRuntime(); try { Process p = rt.exec(checkShellName); if(p.waitFor() != 0) return false; } catch (IOException e) { SysLog.error("沒有找到檢測腳本"); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } return true; } 其中p.waitFor()語句用來等待子進程結束,其返回值為進程結束退出碼。

D. 使用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();
}
}

}

E. java調用shell腳本,並得到shell腳本的返回值

文件名確實不對
.sh文件才是linux下的批處理文件,它不認bat的
另外要保證.sh中調用的其他函數在當前目錄下能正常運行

F. Java解析執行shell命令返回的結果

String s = 那串結果;
String useful = s.substring(s.indexOf("/"));
String[] every = useful.split(" /");
得到的數組就是每個的信息,然後再解析(但要注意,第一個的開頭有一個斜線/)

G. java怎麼調用shell腳本

//用法:Runtime.getRuntime().exec("命令");Stringshpath="/test/test.sh";//程序路徑Processprocess=null;Stringcommand1=「chmod777」+shpath;try{Runtime.getRuntime().exec(command1).waitFor();}catch(IOExceptione1){e1.printStackTrace();}catch(InterruptedExceptione){e.printStackTrace();}Stringvar="201102";/參數Stringcommand2=「/bin/sh」+shpath+」」+var;Runtime.getRuntime().exec(command2).waitFor();

H. 怎麼通過java去調用並執行shell腳本以及問題總結

對於第一個問題:java抓取,並且把結果打包。那麼比較直接的做法就是,java接收各種消息(db,metaq等等),然後藉助於jstorm集群進行調度和抓取。
最後把抓取的結果保存到一個文件中,並且通過調用shell打包, 回傳。 也許有同學會問,
為什麼不直接把java調用odps直接保存文件,答案是,我們的集群不是hz集群,直接上傳odps速度很有問題,因此先打包比較合適。(這里不糾結設計了,我們回到正題)

java調用shell的方法

通過ProcessBuilder進行調度

這種方法比較直觀,而且參數的設置也比較方便, 比如我在實踐中的代碼(我隱藏了部分業務代碼):

ProcessBuilderpb = new ProcessBuilder("./" + RUNNING_SHELL_FILE, param1,
param2, param3);
pb.directory(new File(SHELL_FILE_DIR));
int runningStatus = 0;
String s = null;
try {
Process p = pb.start();
try {
runningStatus = p.waitFor();
} catch (InterruptedException e) {
}

} catch (IOException e) {
}
if (runningStatus != 0) {
}
return;

這里有必要解釋一下幾個參數:

RUNNING_SHELL_FILE:要運行的腳本

SHELL_FILE_DIR:要運行的腳本所在的目錄; 當然你也可以把要運行的腳本寫成全路徑。

runningStatus:運行狀態,0標識正常。 詳細可以看java文檔。

param1, param2, param3:可以在RUNNING_SHELL_FILE腳本中直接通過1,2,$3分別拿到的參數。

直接通過系統Runtime執行shell

這個方法比較暴力,也比較常用, 代碼如下:

p = Runtime.getRuntime().exec(SHELL_FILE_DIR + RUNNING_SHELL_FILE + " "+param1+" "+param2+" "+param3);
p.waitFor();

我們發現,通過Runtime的方式並沒有builder那麼方便,特別是參數方面,必須自己加空格分開,因為exec會把整個字元串作為shell運行。

可能存在的問題以及解決方法

如果你覺得通過上面就能滿足你的需求,那麼可能是要碰壁了。你會遇到以下情況。

沒許可權運行

這個情況我們團隊的朱東方就遇到了, 在做DTS遷移的過程中,要執行包裡面的shell腳本, 解壓出來了之後,發現執行不了。 那麼就按照上面的方法授權吧

java進行一直等待shell返回

這個問題估計更加經常遇到。 原因是, shell腳本中有echo或者print輸出, 導致緩沖區被用完了! 為了避免這種情況, 一定要把緩沖區讀一下, 好處就是,可以對shell的具體運行狀態進行log出來。 比如上面我的例子中我會變成:

ProcessBuilderpb = new ProcessBuilder("./" + RUNNING_SHELL_FILE, keyword.trim(),
taskId.toString(), fileName);
pb.directory(new File(CASPERJS_FILE_DIR));
int runningStatus = 0;
String s = null;
try {
Process p = pb.start();
BufferedReaderstdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReaderstdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = stdInput.readLine()) != null) {
LOG.error(s);
}
while ((s = stdError.readLine()) != null) {
LOG.error(s);
}
try {
runningStatus = p.waitFor();
} catch (InterruptedException e) {
}

記得在start()之後, waitFor()之前把緩沖區讀出來打log, 就可以看到你的shell為什麼會沒有按照預期運行。 這個還有一個好處是,可以讀shell裡面輸出的結果, 方便java代碼進一步操作。

也許你還會遇到這個問題,明明手工可以運行的命令,java調用的shell中某一些命令居然不能執行,報錯:命令不存在!

比如我在使用casperjs的時候,手工去執行shell明明是可以執行的,但是java調用的時候,發現總是出錯。
通過讀取緩沖區就能發現錯誤日誌了。 我發現即便自己把安裝的casperjs的bin已經加入了path中(/etc/profile,
各種bashrc中)還不夠。 比如:

exportNODE_HOME="/home/admin/node"
exportCASPERJS_HOME="/home/admin/casperjs"
exportPHANTOMJS_HOME="/home/admin/phantomjs"
exportPATH=$PATH:$JAVA_HOME/bin:/root/bin:$NODE_HOME/bin:$CASPERJS_HOME/bin:$PHANTOMJS_HOME/bin

原來是因為java在調用shell的時候,默認用的是系統的/bin/下的指令。特別是你用root許可權運行的時候。 這時候,你要在/bin下加軟鏈了。針對我上面的例子,就要在/bin下加軟鏈:

ln -s /home/admin/casperjs/bin/casperjscasperjs;
ln -s /home/admin/node/bin/nodenode;
ln -s /home/admin/phantomjs/bin/phantomjsphantomjs;

這樣,問題就可以解決了。

如果是通過java調用shell進行打包,那麼要注意路徑的問題了

因為shell裡面tar的壓縮和解壓可不能直接寫:

tar -zcf /home/admin/data/result.tar.gz /home/admin/data/result

直接給你報錯,因為tar的壓縮源必須到路徑下面, 因此可以寫成

tar -zcf /home/admin/data/result.tar.gz -C /home/admin/data/ result

如果我的shell是在jar包中怎麼辦?

答案是:解壓出來。再按照上面指示進行操作。(1)找到路徑

String jarPath = findClassJarPath(ClassLoaderUtil.class);
JarFiletopLevelJarFile = null;
try {
topLevelJarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = topLevelJarFile.entries();
while (entries.hasMoreElements()) {
JarEntryentry = entries.nextElement();
if (!entry.isDirectory() entry.getName().endsWith(".sh")) {
對你的shell文件進行處理
}
}

對文件處理的方法就簡單了,直接touch一個臨時文件,然後把數據流寫入,代碼:

FileUtils.touch(tempjline);
tempjline.deleteOnExit();
FileOutputStreamfos = new FileOutputStream(tempjline);
IOUtils.(ClassLoaderUtil.class.getResourceAsStream(r), fos);
fos.close();

I. java 執行shell 腳本 返回 find的內容~~求助

你先列印pathshell這個變數,看這個變數是不是正確的,如果不正確,當然無法定位到find命令了。
你後面的代碼是沒有問題的,只能出在這個地方。
還有你的find命令沒有參數傳入啊,命令參數之類的還是是需要的。

J. shell腳本調用java返回的字元串含有shell變數如何解析

先運行java程序,然後用echo $?獲取程序的運行結果,如果是字元串,可以使用
result=$(java -jar xxx.jar)來獲取,當然這只是示例,$()中的命令使可以隨便修改的

閱讀全文

與java調用shell返回相關的資料

熱點內容
編譯好的android源碼 瀏覽:993
學校機房雲伺服器和電腦主機 瀏覽:10
Python紅色五角星畫法 瀏覽:337
壓縮餅干翻譯 瀏覽:686
macos命令行窗口的樣式 瀏覽:248
androidflipboard 瀏覽:878
投資公司投資源碼 瀏覽:74
python語料訓練 瀏覽:338
武夷岩茶產地溯源碼 瀏覽:383
求生組隊用什麼伺服器最好 瀏覽:24
php回調匿名回調函數 瀏覽:107
源碼翻譯軟體哪裡找 瀏覽:523
邪惡程序員解說 瀏覽:600
醫生找程序員 瀏覽:423
cad三維剖切命令 瀏覽:55
壓縮機的氣能流多遠 瀏覽:85
linuxfdiskt 瀏覽:696
iphone沒有id怎麼用app 瀏覽:983
手機淘寶網站源碼 瀏覽:743
小車上的壓縮機怎麼改氣泵 瀏覽:568