Friday 29 December 2017

Automate Port kill using shell script in Unix/Ubuntu


Many Times, we are getting ''port already in use' while working with server application on different ports.

Find process associated with port and killing that process is time consuming and tedious task.

Solution:

Create port-kill.sh file in home folder and copy below code inside that file.

$sudo gedit ${HOME}/port-kill.sh


for i in "$@"; do
  echo 'killing port= ' $i
  kill -9 $(lsof -t -i:$i)
  #lsof -i -P|grep $i | awk 'NR!=1 {print $2}' | xargs kill -9
  echo 'killed port= ' $i
done



Run port-kill.sh file by passing port number as parameter.

$sh ${HOME}/port-kill.sh <port-numbers-separated-by-space>

For Ex. I want to close process runing on 9000 port number

sachin@sachin-E470:~$ lsof -i -P|grep 9000
java    12335 sachin   31u  IPv6 781666      0t0  TCP *:9000 (LISTEN)
sachin@sachin-E470:~$ sh port-kill.sh 9000 
killing port=  9000

killed port=  9000
sachin@sachin-E470:~$ 
sachin@sachin-E470:~$ lsof -i -P|grep 9000
sachin@sachin-E470:~$ 

ScreenShot:






No comments:

Post a Comment

Extract error records while inserting into db table using JDBCIO apache beam in java

 I was inserting data into postgres db using apache beam pipeline. it works perfectly with JdbcIO write of apache beam library. But, now, i ...