I’m a newbie to shell programming and I’d like to find the IP address from the process ID. Right now, I’m able to get the PID for a specific process from :
vmname=$1
pid=`ps aux | grep $vmname | awk 'NR==1{printf("%s\n", $2) }'`
echo $pid
The above method returns the PID but how do I get the port from the pid? If I get the port, is there a command to get the IP address as well?
I’m using Ubuntu 11.04 and the above script is actually trying to find out the IP of a virtual machine running on KVM using this method.
Thanks!
You can employ the lsof utility. It gives the list of open files for a process. Use lsof -p pid . You need to grep on the output to get the port values for eg. something like this – lsof -p pid| grep TCP. This will list all the ports opened or connected to by the process. Refer to the manual of the utility. For most systems the utility comes pre-bundled with your OS. However, if it is not pre-bundled then you need to install this utility.