欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java執(zhí)行Linux命令簡單代碼舉例

 更新時間:2023年12月09日 10:39:06   作者:baihb1024  
這篇文章主要給大家介紹了關(guān)于Java執(zhí)行Linux命令的相關(guān)資料,在開發(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;
    }
}

二、遠(yuǎn)程執(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é) 

到此這篇關(guān)于Java執(zhí)行Linux命令的文章就介紹到這了,更多相關(guān)Java執(zhí)行Linux命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Map之computeIfAbsent使用解讀

    Map之computeIfAbsent使用解讀

    `computeIfAbsent`是Java 8引入的一個Map接口方法,用于簡化在Map中獲取值的操作,如果指定的鍵不存在,它會調(diào)用提供的函數(shù)生成一個新的值,并將其與鍵關(guān)聯(lián),這種方法減少了手動檢查和插入的樣板代碼,使代碼更加簡潔和易讀
    2025-02-02
  • Java多線程之間日志traceId傳遞方式

    Java多線程之間日志traceId傳遞方式

    這篇文章主要介紹了Java多線程之間日志traceId傳遞方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • SpringAOP中的切點(diǎn)表達(dá)式Pointcut詳解

    SpringAOP中的切點(diǎn)表達(dá)式Pointcut詳解

    這篇文章主要介紹了SpringAOP中的切點(diǎn)表達(dá)式Pointcut詳解,Spring?的?AOP?中的一個核心概念是切點(diǎn)(Pointcut),切點(diǎn)表達(dá)式定義通知(Advice)執(zhí)行的范圍,需要的朋友可以參考下
    2023-08-08
  • SpringBoot整合RabbitMQ實(shí)現(xiàn)消息確認(rèn)機(jī)制

    SpringBoot整合RabbitMQ實(shí)現(xiàn)消息確認(rèn)機(jī)制

    這篇文章主要介紹了SpringBoot整合RabbitMQ實(shí)現(xiàn)消息確認(rèn)機(jī)制,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-08-08
  • Mybatis?sqlMapConfig.xml中的mappers標(biāo)簽使用

    Mybatis?sqlMapConfig.xml中的mappers標(biāo)簽使用

    這篇文章主要介紹了Mybatis?sqlMapConfig.xml中的mappers標(biāo)簽使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教。
    2022-01-01
  • Spring框架中@AliasFor注解詳細(xì)說明

    Spring框架中@AliasFor注解詳細(xì)說明

    這篇文章主要給大家介紹了關(guān)于Spring框架中@AliasFor注解詳細(xì)說明的相關(guān)資料,@AliasFor是Spring Framework中的一個注解,它用于指定注解屬性之間的別名關(guān)系,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2024-02-02
  • SpringMVC post請求的處理

    SpringMVC post請求的處理

    今天小編就為大家分享一篇解決SpringMVC接收不到ajaxPOST參數(shù)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-07-07
  • Java中List集合的常用方法詳解

    Java中List集合的常用方法詳解

    本篇文章給大家?guī)淼膬?nèi)容是關(guān)于Java中List集合的常用方法詳解,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。下面我們就來學(xué)習(xí)一下吧
    2021-11-11
  • springboottest測試依賴和使用方式

    springboottest測試依賴和使用方式

    這篇文章主要介紹了springboottest測試依賴和使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • java實(shí)現(xiàn)讀取、刪除文件夾下的文件

    java實(shí)現(xiàn)讀取、刪除文件夾下的文件

    本文給大家分享的是java實(shí)現(xiàn)讀取、刪除文件夾下的文件,其中File.delete()用于刪除“某個文件或者空目錄”!所以要刪除某個目錄及其中的所有文件和子目錄,要進(jìn)行遞歸刪除,有需要的小伙伴可以參考下。
    2015-05-05

最新評論