㈠ java怎麼調用linux的命令怎麼輸入一條命令讓linux用終端運行,然後獲得返回的文本
用java的process類了。
process這個類是一個抽象類,封裝了一個進程(你在調用linux的命令或者shell腳本就是為了執行一個在linux下執行的程序,所以應該使用process類)。
process類提供了執行從進程輸入,執行輸出到進程,等待進程完成,檢查進程的推出狀態,以及shut down掉進程。
㈡ 如何用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腳本 * @param shell 需要運行的shell腳本 */ public static void execShell(String shell){ try { Runtime rt = Runtime.getRuntime(); rt.exec(shell); } catch (Exception e) { e.printStackTrace(); } }
㈣ 如何用Java寫代碼連上Linux主機去在主機上執行命令
輸入vi HelloWorld.java
進入HelloWorld.java編輯,寫上helloword的代碼
public class Heoolworld{
public static void main(String[] args){
System.out.print("Hello World!");
}
}
按住鍵盤上的esc鍵,然後輸入:wq保存並退出
輸入命令javac HelloWorld.java 編譯Java類
輸入java HelloWorld執行Java類
㈤ 怎麼用java代碼運行linux命令
以下方法支持Linux和windows兩個系統的命令行調用。還用到了apache的lang工具包commons-lang3-3.1.jar來判斷操作系統類型、也用到了和log4j-1.2.16.jar來列印日誌。至於rm -rf 是否能成功刪除文件,可以手動去調用命令行試試。
privateStringcallCmd(Stringcmd)throwsInterruptedException,UnHandledOSException,ExecuteException{
if(SystemUtils.IS_OS_LINUX){
try{
//使用Runtime來執行command,生成Process對象
Processprocess=Runtime.getRuntime().exec(
newString[]{"/bin/sh","-c",cmd});
intexitCode=process.waitFor();
//取得命令結果的輸出流
InputStreamis=process.getInputStream();
//用一個讀輸出流類去讀
InputStreamReaderisr=newInputStreamReader(is);
//用緩沖器讀行
BufferedReaderbr=newBufferedReader(isr);
Stringline=null;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
returnsb.toString();
}catch(java.lang.NullPointerExceptione){
System.err.println("NullPointerException"+e.getMessage());
logger.error(cmd);
}catch(java.io.IOExceptione){
System.err.println("IOException"+e.getMessage());
}
thrownewExecuteException(cmd+"執行出錯!");
}
if(SystemUtils.IS_OS_WINDOWS){
Processprocess;
try{
//process=newProcessBuilder(cmd).start();
String[]param_array=cmd.split("[\s]+");
ProcessBuilderpb=newProcessBuilder(param_array);
process=pb.start();
/*process=Runtime.getRuntime().exec(cmd);*/
intexitCode=process.waitFor();
InputStreamis=process.getInputStream();
InputStreamReaderisr=newInputStreamReader(is);
BufferedReaderbr=newBufferedReader(isr);
Stringline;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
returnsb.toString();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
thrownewExecuteException(cmd+"執行出錯!");
}
thrownewUnHandledOSException("不支持本操作系統");
}
㈥ java怎麼執行linux互動式命令
Process prc = runtime.exec(.....); prc.waitFor();//這行就能阻塞後續代碼的執行,直到你執行的命令結束。
㈦ java程序里調用linux命令
Java語言以其跨平台性和簡易性而著稱,在Java裡面的lang包里(java.lang.Runtime)提供了一個允許Java程序與該程序所運
行的環境交互的介面,這就是Runtime類,在Runtime類里提供了獲取當前運行環境的介面。
其中的exec函數返回一個執行shell命令的子進程。exec函數的具體實現形式有以下幾種:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws
IOException
public Process exec(String command,String[] envp,File dir) throws
IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws
IOException
public Process exec(String[] cmdarray, String[] envp,File dir)
throws IOException
我們在這里主要用到的是第一個和第四個函數,具體方法很簡單,就是在exec函數中傳遞一個代表命令的字元串。exec函數返回的是一個Process類
型的類的實例。Process類主要用來控制進程,獲取進程信息等作用。(具體信息及其用法請參看Java doc)。
1)執行簡單的命令的方法:
代碼如下:
㈧ 如何在java程序中調用linux命令或者shell腳本
在java程序中如何調用linux的命令?如何調用shell腳本呢?
這里不得不提到java的process類了。
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的方式。
下面說一下,如何使用process來調用shell腳本
例如,我需要在linux下實行linux命令:sh test.sh,下面就是執行test.sh命令的方法:
這個var參數就是日期這個201102包的名字。
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();
注意:
1
我為什麼要使用 chmod 777命令呢?在有的機器上面,可能沒有設置許可權問題。這是你在linux下面執行shell腳本需要注意的問題。沒有的話,就需要添加許可權,就用chmod 777,否則在執行到Runtime.getRuntime().exec的時侯會出現Permission denied錯誤。
2
waitFor()這個也是必不可缺的,如果你需要執行多行命令的話,把waitFor()這個加上。
㈨ java程序執行linux命令
首先確保Linux開啟sshd服務,並支持遠程SSH連接。java程序使用jsch框架登錄Linux,執行命令。
protected void creation() throws Exception {
JSch jsch = new JSch();
session = jsch.getSession(userName, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(CONNECT_TIMEOUT);
session.setConfig("PreferredAuthentications", "password,keyboard-interactive");
session.setServerAliveInterval(1000 * 60 * 2);
session.connect();
}
public String sendCommand(String command) throws Exception {
if(!isConnected())
throw new JSchException("Session is not connected, command exec faild.");
final ChannelExec exec = (ChannelExec)session.openChannel("exec");
ByteArrayOutputStream out = new ByteArrayOutputStream();
exec.setCommand(command);
exec.setOutputStream(out);
exec.setExtOutputStream(out);
exec.connect();
final Thread thread = new Thread() {
public void run() {
while(!exec.isEOF()) {
try { Thread.sleep(500L); } catch(Exception e) {}
}
}
};
thread.setDaemon(true);
thread.start();
thread.join(EXEC_TIMEOUT);
thread.interrupt();
if(thread.isAlive()) {
throw new JSchException("Exec Time Out Error");
} else {
try {
exec.disconnect();
out.close();
} catch (Exception e) {
}
byte[] lens = out.toByteArray();
String result = new String(lens, charset);
if(result.startsWith("bash") && result.indexOf("command not found") != -1)
return "";
return result;
}
}