導航:首頁 > 編程語言 > javalinux執行shell

javalinux執行shell

發布時間:2023-02-28 02:28:27

Ⅰ 如何用java調用linux shell命令

代碼方法如下:
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);
}
}
}

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

Ⅳ 如何用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();
閱讀全文

與javalinux執行shell相關的資料

熱點內容
五十音圖pdf 瀏覽:865
什麼叫下架伺服器 瀏覽:111
pdf解析度查看 瀏覽:15
如何將word轉pdf 瀏覽:186
我的世界ec伺服器怎麼調配置 瀏覽:259
單片機換標 瀏覽:595
語音系統和方舟編譯器哪個好 瀏覽:316
html用什麼編譯器顯示 瀏覽:185
程序員列印系統 瀏覽:73
安裝系統埠和伺服器地址怎麼看 瀏覽:263
編譯指針 瀏覽:410
用於解壓房款的擔保協議 瀏覽:672
程序員補班 瀏覽:564
組件編譯語言 瀏覽:815
c文件夾怎麼復制 瀏覽:966
linux統計ip流量 瀏覽:997
905減407的豎式演算法 瀏覽:647
我的世界網易版如何查看伺服器種子 瀏覽:632
施工現場臨時水管直徑演算法 瀏覽:5
如何刷新伺服器redis緩存 瀏覽:502