Java執(zhí)行Linux命令簡單代碼舉例
更新時間:2023年12月09日 10:39:06 作者:baihb1024
這篇文章主要給大家介紹了關于Java執(zhí)行Linux命令的相關資料,在開發(fā)的過程中要善于利用JAVA面向?qū)ο缶幊痰膬?yōu)勢,與Linux/Unix命令或Shell腳本的優(yōu)勢,并將二者相結(jié)合,需要的朋友可以參考下
一、本地執(zhí)行 Linux 命令
1. 執(zhí)行單條命令
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellUtil {
public void execCmd(String cmd) throws IOException {
Runtime run = Runtime.getRuntime();
Process proc = null;
BufferedReader br = null;
InputStream in = null;
try {
proc = run.exec(cmd, null, null);
in = proc.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
String result;
while ((result = br.readLine()) != null) {
System.out.println("job result [" + result + "]");
}
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (proc != null)
proc.destroy();
if (in != null)
in.close();
if (br != null)
br.close();
}
}
}
2. 執(zhí)行含有管道符(|)的多級命令
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ShellUtil {
public List<String> execCmd(String cmd) throws IOException {
List<String> list = new ArrayList<>();
Runtime run = Runtime.getRuntime();
Process proc = null;
BufferedReader br = null;
InputStream in = null;
try {
proc = run.exec(new String[]{"/bin/sh", "-c", cmd});
in = proc.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
String result;
while ((result = br.readLine()) != null) {
System.out.println("job result [" + result + "]");
list.add(result);
}
proc.waitFor();
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (proc != null)
proc.destroy();
if (in != null)
in.close();
if (br != null)
br.close();
}
return list;
}
}
3. 執(zhí)行多條命令
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class ShellUtil {
/**
* 命令集合
*/
public static List<String> getCommandList() {
String path = "/root";
List<String> commands = new ArrayList<>();
commands.add("cd " + path);
commands.add("ls");
return commands;
}
/**
* 執(zhí)行命令
*/
public static List<String> execCommands(List<String> commands) throws IOException {
List<String> list = new ArrayList<>();
Runtime run = Runtime.getRuntime();
Process proc = null;
BufferedReader in = null;
PrintWriter out = null;
try {
proc = run.exec("/bin/bash", null, null);
in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
// 寫入執(zhí)行命令
for (String line : commands) {
out.println(line);
}
// 這個命令必須執(zhí)行,否則 in 流不結(jié)束
out.println("exit");
String line;
while ((line = in.readLine()) != null) {
System.out.println("readLine: " + line);
list.add(line);
}
// 釋放資源
proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (proc != null)
proc.destroy();
if (in != null)
in.close();
if (out != null)
out.close();
}
return list;
}
}
二、遠程執(zhí)行 Linux 命令
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>262</version>
</dependency>
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LinuxUtil {
public static void main(String[] args) {
String hostname = "127.0.0.1";
String username = "root";
String password = "123456";
try {
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (!isAuthenticated) {
throw new IOException("Authentication failed");
}
Session sess = conn.openSession();
// 命令語句,必須使用絕對路徑否則無效(環(huán)境變量也不可以)。如:java --version
sess.execCommand("pwd");
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
// 輸出命令執(zhí)行結(jié)果
System.out.println(line);
}
sess.close();
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
}總結(jié)
到此這篇關于Java執(zhí)行Linux命令的文章就介紹到這了,更多相關Java執(zhí)行Linux命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java 中的 @SneakyThrows 注解的使用方法(簡化異常處理的利與弊)
@SneakyThrows是Lombok提供的一個注解,用于簡化Java方法中的異常處理,特別是對于檢查型異常,它允許方法拋出異常而不必顯式聲明或捕獲這些異常,本文介紹Java 中的 @SneakyThrows 注解的使用方法,感興趣的朋友一起看看吧2025-03-03
如何解決maven搭建一直處于running:..狀態(tài)問題
在使用Maven搭建項目時,有時會遇到一直處于加載狀態(tài)的情況,通過修改設置可以解決這個問題,具體步驟為:1. 打開File->Settings->Build, Execution, Deployment->Maven->running,然后在VMOptions中填寫"-DarchetypeCatalog=internal"2024-09-09

