shell脚本同时查看进程和端口号

编写一个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"

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/212287
  • 你也可以参考下这篇文章:Java代码调用本地shell命令或shell脚本
  • 除此之外, 这篇博客: 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");


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^