Search code examples
linuxansibleportpidnetstat

Showing multiple java processes with different pids


I want to fetch all running ports with service name but some ports name are java.

Below given ports are fetching using ansible.

ansible -m listen_ports_facts --user=username --become --ask-become-pass --tree portdir/ all

tcp : 8011 : java

tcp : 8012 : java

tcp : 8013 : java

How can I do it? Please suggest on the same.

I have tried with ps -aux | grep "PID" and found that there is directory path.


Solution

  • Because Java is like a VM you cannot really see what the Java Process is serving without knowledge about the process itself. Normally you run a Java VM with parameters - something like java -jar /path/to/my/program.jar or in case of Wildfly etc. some params show a path to standaloneor what ever. This parameter can give you a hint, what is the JavaVM is running. But that's not easy to filter in a general way.

    Also some Java processes are opening multiple port under the same PID (like Wildfly opens ports to serve the Java-Webcontainer and also to some management web UIs etc).

    So, the quick answer is - no - you cannot find out generally what is a Java VM serving by examinating the ports. But maybe in case of SpringBoot you could match the service name against the parameter value of -jar <program>.jar and then the is the name of the service. Also - for example in case of Tomcat - there is no -jar parameter but a class name like java -cp ... -D..=.. org.apache.catalina.startup.Bootstrap .. - which shows you, that this is a Tomcat (codename Catalina). I'm not sure if there is an easy/exact way to identify the classname parameter...

    In some cases this will not help you - because there could be multiple ports and maybe some PIDs serving the same <program>. Either you life with that (for example you say, it is serving a Wildfly or a Tomcat on Port 8011. That is generic.

    If you need to know, what is on that port - it could be possible to either parse the configuration of that programs (which means you need knowledge about the process structure) - for example a Tomcat stores it Webcontainers under /webapps/*.war. And because it could be more then one service (war) running there, the port could be not unique to "one" service.

    If your Java processes are using always the same port, you could add this ports to /etc/services or make a dict in your environment with key=port, value=servicename to map the port-servicename mapping statically. Also you could add a warning, when a port-servicename isn't matching.