sunhux
asked on
Shell / Perl script to test a Tcp port using nc netcat in RHES 4.x
I have an application that often fails to respond (though 'ps -ef |grep pid'
showed the app's process is still there), so under such circumstance I
would run the 'shutdown' script & 'startup' sript to restart TO IX IT
I'll need a sript that checks every 20 secs using nc / netcat for say
Tcp port 3211 every 20 secs in the LINUX server & if it does not
respond, then this sript wll do the restart
Cron can schedule to run every minute, so this script will
have to do a 'sleep 20' twice so as to be able to check the
port every 20 secs
I think it should be ... $(seq 2) ...
Nope. $(seq 3) was correct (I guess ...)
... but the second "sleep" at the end should rather be "sleep 17" to take the 2-second sleep after "telnet" and some processing time into account.
ASKER
My apologies, I just realized this java app listens on 3 ports,
ie tcp 8905, 8205 & 8209. So if it fails to listen to any one of
the ports, we'll need a restart (so an OR test is needed) :
# netstat -antp | grep -i listen | grep -i jav
tcp 0 0 :::8905 :::* LISTEN 7601/java
tcp 0 0 ::ffff:127.0.0.1:8205 :::* LISTEN 7601/java
tcp 0 0 :::8209 :::* LISTEN 7601/java
Would you be able to re-amend the script to cater for this?
Thanks for yr patience
ASKER
& the 'ps -ef' output if it helps with the scripting:
# ps -ef | grep 7601
appusr 7601 1 0 Jul01 ? 00:51:01 /opt/java/bin/java -Xms1024m -Xmx1024m -Djava.awt.headless=true -classpath /app/forum/common/lib/SASe
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
excellent
I once wrote the below script to solve another issue here at EE. It uses telnet instead of nc, however.
I modified it a bit so it might be able to suit your needs.
#!/bin/ksh
CHECKFILE=/tmp/portchk.$$
PORT=3211
HOST=localhost
SLEEPTIME=2 # This is not the sleeptime to overcome cron's 1-minute restriction!
for i in $(seq 3)
do
rm $CHECKFILE 2>/dev/null
( telnet $HOST $PORT 2>&1 ) > $CHECKFILE &
JOB=$!
sleep $SLEEPTIME
kill $JOB 2>/dev/null
if grep -q "Connected to" $CHECKFILE ; then
echo Application on port $PORT is still responding.
else
echo Application on port $PORT is down. Restarting ...
/path/to/shutdown.sh
/path/to/startup.sh
echo Restart done.
fi
rm $CHECKFILE 2>/dev/null
sleep 20
done
wmp