编写一个shell脚本,能够同时查看出进程名称和端口号?例如查看java进程,只要运行下脚本,可以看到所有java进程,正在运行的jar路径,端口号。
#!/bin/bash
java_proc=$(ps aux | grep -i java | grep -v grep)
while read -r line; do
pid=$(echo "$line" | awk '{print $2}')
pn=$(echo "$line" | awk '{print $11}')
cmdline=$(echo "$line" | awk '{print $12}')
jar_path=$(echo "$cmdline" | grep -o -P "(?<=-jar ).*\.jar")
port=$(sudo netstat -tlnp | awk -v pid="$pid" '$0 ~ pid {gsub(/[^0-9]/,"",$4); print $4}')
echo "进程名称: $pn"
echo "正在运行的jar路径: $jar_path"
echo "端口号: $port"
done <<< "$java_proc"
不知道你这个问题是否已经解决, 如果还没有解决的话:参数为脚本路径,脚本内容就不贴了
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");