当前位置:   article > 正文

Java 执行 Linux 命令_java执行linux命令行

java执行linux命令行

一、本地执行 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();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

二、远程执行 Linux 命令

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
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);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/84243
推荐阅读
相关标签
  

闽ICP备14008679号