Bash – Checking the status of custom services with a script

bashscriptingshell-script

I have a handful of shell scripts that start WebLogic managed servers. I need to design a master script that does the following:

  • Executes the shell script for a component\managed server
  • Checks to see if the port for that component is listening for 2 minutes (this can be any value but none of these services should take longer than 2 mins to start)
  • If the service starts within the 2 minutes, continue on and start the next service otherwise write a log message that the service failed to start and then continue on

The script will look something like this:

svcs = some_array_of_svcs

log  = '/path_to_log/log.txt'

' start each service'
for each $svc in $svcs
   echo "starting $svc" >> ${log}
   . /path_to_scripts/$svc
' check to see if the service started
loop for max 2 mins
   if port is listening
      echo 'Service started successfully' >> ${log}
      start the next service
   else
      echo 'Service did not start within the specified timeout' >> ${log}
      start the next service
   end if
next

I need the code to check the port status for n minutes per service.

Best Answer

netcat to the rescue... Netcat is very similar to telnet, but with a few extra crazy options. One of particular use in this case is -z, which just checks to see if the connection works. Along with the timeout variable, you can have the system repeatedly check if the service is listening.

I have ssh enabled locally, but not telnet.

$ nc -zw10 localhost 22
$ echo $?
0
$ nc -zw10 localhost 23
$ echo $?
1

And for the a bit more clarity on the testing... This is assuming the 2 minute timeout you mentioned earlier. It checks 4 times with half a minute timeout each time. Datestamps would likely be better, but this is a start.

for i in {1..4}; do
  nc -zw30 localhost 22
  x=$?
  [[ $x -eq 0 ]] && break
done
if [[ $x -eq 0 ]]; then
  echo 'Service started successfully' >> ${log}
else
  echo 'Service did not start within the specified timeout' >> ${log}
fi
start next service
Related Question