Java 执行 Shell 命令

package com.base.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class ShellUtil {

    private String getOs(){
        return System.getProperty("os.name");
    }

    /** Returns null if it failed for some reason.*/
    public ArrayList<String> execCommand(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) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.
            return null;
        }
    }

    public ArrayList<String> execCommandAllPlatforms(String cmdline){
        if(getOs().contains("Mac OS X")){
            return null;
        }
        return  execCommand(cmdline, ".");
    }

    public String getLocalIp(){
        String command="ifconfig eth0 | grep \"inet\\ \"| awk '{ print $2}'";
        if(getOs().contains("Mac OS X")){
            command="ifconfig en0 | grep \"inet\\ \" | awk '{ print $2}'";
        }
        return execCommand(command, ".").get(0);
    }

}

测试代码

package com.service;

import com.base.utils.ShellUtil;

public class MainTest {

    public static void main(String[] args) {
        testShell();
    }

    public static void testShell(){
        ShellUtil shellUtil = new ShellUtil();
        System.out.println("IP:"+shellUtil.getLocalIp());
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java可以通过使用Runtime.getRuntime().exec()方法来执行shell命令。 例如: ``` String command = "ls -l"; Process process = Runtime.getRuntime().exec(command); ``` 这会在Java程序中执行“ls -l”命令,然后将执行结果保存在Process对象中。 可以使用process.getInputStream()获取命令的标准输出,使用process.getErrorStream()获取错误信息。 例如: ``` BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } ``` 注意: 使用java执行shell命令时,要格外小心,因为任何人都可能提供恶意的命令来攻击你的系统。 ### 回答2: Java是一种高级编程语言,它的运用范围非常广泛,可以用于开发各种程序和应用,而掌握Java执行shell命令的技能也是非常重要的。 在Java中,我们可以使用Runtime类和Process类来执行shell命令。Runtime类表示Java应用程序的运行时环境,可以运行操作系统命令,而Process类则表示正在运行的进程。 执行shell命令的基本流程如下: 1.创建一个Runtime对象 Runtime runtime = Runtime.getRuntime(); 2.调用Runtime对象的exec()方法,传入要执行shell命令 Process process = runtime.exec("要执行shell命令"); 注意:要执行shell命令必须符合操作系统的语法规则。 3.获取Process对象的输入输出流 InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); OutputStream outputStream = process.getOutputStream(); 4.读取输入输出流,获取shell命令的返回结果 可以使用Java的IO流来读取输入输出流中的数据。如果需要向shell命令传递参数,可以使用输出流将参数写入。 5.关闭流和进程 一定要注意关闭输入输出流和进程,以防止资源泄漏。 以上就是Java执行shell命令的基本步骤,使用时需要注意一些细节。此外,Java执行shell命令也存在一些安全风险,需要合理使用,避免恶意操作。 ### 回答3: Java可以执行外部操作系统命令,包括shell命令Java提供了一个方便的类Runtime,该类允许您从Java程序中执行命令。您还可以使用ProcessBuilder类来执行命令,但该类提供了更多控制和更好的错误处理能力。 使用Runtime类执行shell命令 使用Runtime类的exec()方法可以从Java程序中执行shell命令。以下是使用Runtime类执行shell命令的代码示例: ``` import java.io.BufferedReader; import java.io.InputStreamReader; public class RunShellCommand { public static void main(String[] args) { String command = "ls -l"; // shell命令 try { // 执行命令 Process process = Runtime.getRuntime().exec(command); // 读取命令输出信息 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待命令执行完成 process.waitFor(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们使用Runtime类的exec()方法执行shell命令“ls -l”。在执行命令后,我们使用BufferedReader类读取输出信息。最后,我们等待命令的完成,使用waitFor()方法。 使用ProcessBuilder类执行shell命令 ProcessBuilder类提供了更多的控制和错误处理能力,尤其是在需要传递参数和环境变量时。以下是使用ProcessBuilder类执行shell命令的代码示例: ``` import java.io.BufferedReader; import java.io.InputStreamReader; public class RunShellCommand { public static void main(String[] args) { String command = "ls"; try { // 构建命令 ProcessBuilder builder = new ProcessBuilder(command); // 读取命令输出信息 builder.redirectErrorStream(true); Process process = builder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } // 等待命令执行完成 process.waitFor(); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们使用ProcessBuilder类的start()方法执行shell命令“ls”。在执行命令后,我们使用BufferedReader类读取输出信息。最后,我们等待命令的完成,使用waitFor()方法。 总结 Java可以方便地执行shell命令,并提供了两种执行命令的方式。使用Runtime类的exec()方法可以执行简单的shell命令,而ProcessBuilder类则提供了更多的控制和错误处理能力。无论使用哪种方法,都需要小心处理命令的输入和输出,以避免出现安全问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值