需求

   忽然想写个东西,然后发现自己的linux中端口开放问题以及端口占用问题很麻烦,因为我经常用8080端口,如果有一个图形化界面看某个端口被占用以及被什么占用就好了。

落地实现

(1)直接执行shell命令(参数为命令)

ShellUtils.exceShell("ls -l /");
package com.example.portinterpretationplugin.utils;

import com.example.portinterpretationplugin.constant.ShellConstant;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
* @author chaird
* @create 2020-10-11 15:53
*/
public class ShellUtils {




/**
* @param pathOrCommand 脚本路径或者命令
* @return
*/
public static List<String> exceShell(String pathOrCommand) {
List<String> result = new ArrayList<>();

try {
// 执行脚本
Process ps = Runtime.getRuntime().exec(pathOrCommand);
int exitValue = ps.waitFor();
if (0 != exitValue) {
System.out.println("call shell failed. error code is :" + exitValue);
}

// 只能接收脚本echo打印的数据,并且是echo打印的最后一次数据
BufferedInputStream in = new BufferedInputStream(ps.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
System.out.println("脚本返回的数据如下: " + line);
result.add(line);
}
in.close();
br.close();

} catch (Exception e) {
e.printStackTrace();
}

return result;
}
}

日志打印结果如下

Java中运行shell脚本_数据

(2)直接执行shell脚本(参数为脚本路径)

参数为脚本路径,脚本内容就不贴了

ShellUtils.exceShell("/opt/project/firewalld_status.sh");
package com.example.portinterpretationplugin.utils;

import com.example.portinterpretationplugin.constant.ShellConstant;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
* @author chaird
* @create 2020-10-11 15:53
*/
public class ShellUtils {




/**
* @param pathOrCommand 脚本路径或者命令
* @return
*/
public static List<String> exceShell(String pathOrCommand) {
List<String> result = new ArrayList<>();

try {
// 执行脚本
Process ps = Runtime.getRuntime().exec(pathOrCommand);
int exitValue = ps.waitFor();
if (0 != exitValue) {
System.out.println("call shell failed. error code is :" + exitValue);
}

// 只能接收脚本echo打印的数据,并且是echo打印的最后一次数据
BufferedInputStream in = new BufferedInputStream(ps.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
System.out.println("脚本返回的数据如下: " + line);
result.add(line);
}
in.close();
br.close();

} catch (Exception e) {
e.printStackTrace();
}

return result;
}
}

前提是:你的脚本有权限去运行,即在linux上有权限去运行,否则不通;

如果不满足,如果不满足,下下策为执行脚本之前先执行以下赋予权限的命令 ,在执行你的命令

ShellUtils.exceShell("chmod -R 777 /opt/project/firewalld_status.sh");
ShellUtils.exceShell("/opt/project/firewalld_status.sh");

(3)脚本在项目里(在jar包里)

(1)复制sh到操作系统的某个目录下(亲测,可用)

     ​​从jar包内复制文件到系统目录内_CBeann的博客-_java将jar包中文件复制到​

(2)用方式二执行脚本

参考

​java去调用并执行shell脚本以及问题总结_vcfriend的专栏java 运行shell脚本​

​从jar包内复制文件到系统目录内_CBeann的博客-_java将jar包中文件复制到​