導航:首頁 > 編程語言 > java代碼如何執行shell命令

java代碼如何執行shell命令

發布時間:2023-06-26 09:32:22

❶ 請教個java調用shell命令操作

近日項目中有這樣一個需求:系統中的外幣資金調度完成以後,要將調度信息生成一個Txt文件,然後將這個Txt文件發送到另外一個系統(Kondor)中。生成文件自然使用OutputStreamWirter了,發送文件有兩種方式,一種是用寫個一個類似於FTP功能的程序,另外一種就是使用Java來調用Shell,在Shell中完成文件的發送操作。我們選擇後一種,即當完成外幣資金的調度工作後,用Java的OutputStreamWriter來生成一個Txt文件,然後用Java來調用Shell腳本,在Shell腳本中完成FTP文件到Kondor系統的工作。
以下為Java程序JavaShellUtil.java:import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaShellUtil {
//基本路徑
private static final String basePath = "/tmp/";

//記錄Shell執行狀況的日誌文件的位置(絕對路徑)
private static final String executeShellLogFile = basePath + "executeShell.log";

//發送文件到Kondor系統的Shell的文件名(絕對路徑)
private static final String sendKondorShellName = basePath + "sendKondorFile.sh";

public int executeShell(String shellCommand) throws IOException {
int success = 0;
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = null;
//格式化日期時間,記錄日誌時使用
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");

try {
stringBuffer.append(dateFormat.format(new Date())).append("准備執行Shell命令 ").append(shellCommand).append(" \r\n");

Process pid = null;
String[] cmd = {"/bin/sh", "-c", shellCommand};
//執行Shell命令
pid = Runtime.getRuntime().exec(cmd);
if (pid != null) {
stringBuffer.append("進程號:").append(pid.toString()).append("\r\n");
//bufferedReader用於讀取Shell的輸出內容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
pid.waitFor();
} else {
stringBuffer.append("沒有pid\r\n");
}
stringBuffer.append(dateFormat.format(new Date())).append("Shell命令執行完畢\r\n執行結果為:\r\n");
String line = null;
//讀取Shell的輸出內容,並添加到stringBuffer中
while (bufferedReader != null &
&
(line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("\r\n");
}
} catch (Exception ioe) {
stringBuffer.append("執行Shell命令時發生異常:\r\n").append(ioe.getMessage()).append("\r\n");
} finally {
if (bufferedReader != null) {
OutputStreamWriter outputStreamWriter = null;
try {
bufferedReader.close();
//將Shell的執行情況輸出到日誌文件中
OutputStream outputStream = new FileOutputStream(executeShellLogFile);
outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(stringBuffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStreamWriter.close();
}
}
success = 1;
}
return success;
}

}

以下是Shell腳本sendKondorFile.sh,該Shell腳本的作用是FTP文件到指定的位置:
#!/bin/sh

#日誌文件的位置
logFile="/opt/fms2_kondor/sendKondorFile.log"

#Kondor系統的IP地址,會將生成的文件發送到這個地址
kondor_ip=192.168.1.200

#FTP用戶名
ftp_username=kondor

#FTP密碼
ftp_password=kondor

#要發送的文件的絕對路徑
filePath=""

#要發送的文件的文件名
fileName=""

#如果Shell命令帶有參數,則將第一個參數賦給filePath,將第二個參數賦給fileName
if [ $# -ge "1" ]
then
filePath=$1
else
echo "沒有文件路徑"
echo "沒有文件路徑\n" >
>
$logFile
return
fi

if [ $# -ge "2" ]
then
fileName=$2
else
echo "沒有文件名"
echo "沒有文件名\n" >
>
$logFile
return
fi

echo "要發送的文件是 ${filePath}/${fileName}"

cd ${filePath}
ls $fileName
if (test $? -eq 0)
then
echo "准備發送文件:${filePath}/${fileName}"
else
echo "文件 ${filePath}/${fileName} 不存在"
echo "文件 ${filePath}/${fileName} 不存在\n" >
>
$logFile
return
fi

ftp -n ${kondor_ip} <
<
_end
user ${ftp_username} ${ftp_password}
asc
prompt
put $fileName
bye
_end

echo "`date +%Y-%m-%d' '%H:%M:%S` 發送了文件 ${filePath}/${fileName}"
echo "`date +%Y-%m-%d' '%H:%M:%S` 發送了文件 ${filePath}/${fileName}\n" >
>
$logFile

調用方法為:
JavaShellUtil javaShellUtil = new JavaShellUtil();
//參數為要執行的Shell命令,即通過調用Shell腳本sendKondorFile.sh將/temp目錄下的tmp.pdf文件發送到192.168.1.200上
int success = javaShellUtil.executeShell("sh /tmp/sendKondorFile.sh /temp tmp.pdf");

❷ 如何在java中執行shell腳本

1、最常用的方法:

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

2、通過ProcessBuilder進行調度,這種方法比較直觀,而且參數的設置也比較方便:

ProcessBuilderpb=newProcessBuilder("./"+RUNNING_SHELL_FILE,param1,
param2,param3);
pb.directory(newFile(SHELL_FILE_DIR));
intrunningStatus=0;
Strings=null;
try{
Processp=pb.start();
try{
runningStatus=p.waitFor();
}catch(InterruptedExceptione){
e.printStackTrace();
}
}catch(IOExceptione){
e.printStackTrace();
}
if(runningStatus!=0){

}
return;

參數說明:
RUNNING_SHELL_FILE:要運行的腳本
SHELL_FILE_DIR:要運行的腳本所在的目錄; 當然你也可以把要運行的腳本寫成全路徑。
runningStatus:運行狀態,0標識正常。 詳細可以看java文檔。
param1, param2, param3:可以在RUNNING_SHELL_FILE腳本中直接通過1,1,2,$3分別拿到的參數。

❸ 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()語句用來等待子進程結束,其返回值為進程結束退出碼。

❹ 如何用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);
}
}
}

註:參數中逗/bin/sh逗 逗-c逗 是可以用shell執行指定的命令的意思
這里/bin/sh -cps -ef|grep java,會執行ps linux命令

閱讀全文

與java代碼如何執行shell命令相關的資料

熱點內容
岳陽微信公司 瀏覽:96
win10如何從備份中恢復出廠設置密碼 瀏覽:659
什麼軟體修改wifi密碼錯誤 瀏覽:582
遇見不安全網站怎麼辦 瀏覽:251
哪個app有慶余年電視劇 瀏覽:420
iphone5s視頻時很黑 瀏覽:601
js獲取埠號 瀏覽:347
手機短息發的鏈接病毒蘋果手機 瀏覽:724
win10專業忘記家庭組密碼 瀏覽:176
南寧applestore幾樓 瀏覽:296
java字元串怎麼初始化 瀏覽:349
醫美哪個app好 瀏覽:768
代碼編程和機器人編程哪個好 瀏覽:875
90版本男法 瀏覽:796
win10桌面字體難看 瀏覽:848
三菱fx5u支持哪些編程 瀏覽:7
優酷在文件夾在哪裡 瀏覽:91
趣列印的數據文件是什麼 瀏覽:871
linuxjava程序 瀏覽:483
蘋果6splus數據線圖片 瀏覽:98

友情鏈接