Java执行Linux命令简单代码举例

 更新时间:2023年12月09日 10:39:06   作者:baihb1024  
这篇文章主要给大家介绍了关于Java执行Linux命令的相关资料,在开发的过程中要善于利用JAVA面向对象编程的优势,与Linux/Unix命令或Shell脚本的优势,并将二者相结合,需要的朋友可以参考下

一、本地执行 Linux 命令

1. 执行单条命令

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. 执行含有管道符(|)的多级命令

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. 执行多条命令

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;
    }


    /**
     * 执行命令
     */
    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);

            // 写入执行命令
            for (String line : commands) {
                out.println(line);
            }
            // 这个命令必须执行,否则 in 流不结束
            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;
    }
}

二、远程执行 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();

            // 命令语句,必须使用绝对路径否则无效(环境变量也不可以)。如: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;
                }
                
                // 输出命令执行结果
                System.out.println(line);
            }
            sess.close();
            conn.close();
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(2);
        }
    }
}

总结 

到此这篇关于Java执行Linux命令的文章就介绍到这了,更多相关Java执行Linux命令内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • JAVA及相关字符集编码问题研究分享

    JAVA及相关字符集编码问题研究分享

    对于JAVA学习,或多或少都会遇到这样的问题:编码基本知识,java,系统软件,url,工具软件等
    2014-10-10
  • Java 中的 @SneakyThrows 注解的使用方法(简化异常处理的利与弊)

    Java 中的 @SneakyThrows 注解的使用方法(简化异常处理的利与弊)

    @SneakyThrows是Lombok提供的一个注解,用于简化Java方法中的异常处理,特别是对于检查型异常,它允许方法抛出异常而不必显式声明或捕获这些异常,本文介绍Java 中的 @SneakyThrows 注解的使用方法,感兴趣的朋友一起看看吧
    2025-03-03
  • Spring的@Conditional详解

    Spring的@Conditional详解

    这篇文章主要介绍了Spring的@Conditional详解,给想要注入Bean增加限制条件,只有满足限制条件才会被构造并注入到Spring的IOC容器中,通常和@Bean注解一起使用,需要的朋友可以参考下
    2024-01-01
  • Java对称与非对称加密算法原理详细讲解

    Java对称与非对称加密算法原理详细讲解

    对称加密算法指加密和解密使用相同密钥的加密算法。对称加密算法用来对敏感数据等信息进行加密,非对称加密算法指加密和解密使用不同密钥的加密算法,也称为公私钥加密
    2022-11-11
  • Java中遍历Map集合的5种方式总结

    Java中遍历Map集合的5种方式总结

    这篇文章主要给大家介绍了关于Java中遍历Map集合的5种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Java Http多次请求复用同一连接示例详解

    Java Http多次请求复用同一连接示例详解

    这篇文章主要为大家介绍了Java Http多次请求复用同一连接示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-10-10
  • 如何解决maven搭建一直处于running:..状态问题

    如何解决maven搭建一直处于running:..状态问题

    在使用Maven搭建项目时,有时会遇到一直处于加载状态的情况,通过修改设置可以解决这个问题,具体步骤为:1. 打开File->Settings->Build, Execution, Deployment->Maven->running,然后在VMOptions中填写"-DarchetypeCatalog=internal"
    2024-09-09
  • Java集合Iterator迭代的实现方法

    Java集合Iterator迭代的实现方法

    这篇文章主要介绍了Java集合Iterator迭代接口的实现方法,非常不错,具有参考借鉴家,对Java 结合iterator知识感兴趣的朋友一起看看吧
    2016-08-08
  • java连接Mongodb实现增删改查

    java连接Mongodb实现增删改查

    这篇文章主要为大家详细介绍了java连接Mongodb实现增删改查,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-03-03
  • Spring Boot 中使用cache缓存的方法

    Spring Boot 中使用cache缓存的方法

    Spring Cache是Spring针对Spring应用,给出的一整套应用缓存解决方案。下面小编给大家带来了Spring Boot 中使用cache缓存的方法,感兴趣的朋友参考下吧
    2018-01-01

最新评论