2

I have to write a maintenance script that iterates over our IPs testing their connectivity to certain services such as nc -sip# mailin-01.mx.aol.com 25.

It has a flag -w ... but it's not what I think it is. That is, I only want this program to run for at max 3 seconds and the places we are connecting to are always up (unless major network problems that the script shouldn't worry about --- not its particular job and would be noticed before the script is run).

I just need it to connect and see if we are getting an error message. This is required before we assign an IP to a user for their web page (this is an alternative to CPanel stuff -- we want our own).

slm
  • 369,824
Arian
  • 339
  • 2
    Why wouldn't you just store the IPs you have assigned out as you assign them? This is very unreliable and will not scale well. You are writing a web hosting control panel and this is the part you are stuck on? – jordanm Oct 20 '13 at 03:36
  • I'm not writing the panel, I'm writing some utilities. What does your comment about storing have anything to do with the answer? – Arian Oct 20 '13 at 04:07

2 Answers2

2

The simplest way of doing this is with the timeout command. The timeout command lets you run a specified command, and if that command doesn't exit own it's own within a certain timeout, timeout kills it.

For example

# timeout 3 sleep 1; echo exit=$? 
exit=0

# timeout 3 sleep 5; echo exit=$?
exit=124

# timeout 3 nc google.com 80; echo exit=$?
nc: using stream socket
exit=124

timeout is not defined in the POSIX standard, so it's not guaranteed to be everywhere, but it seems to be prevalent.

phemmer
  • 71,831
1

http://www.varesano.net/blog/fabio/executing-program-x-seconds-then-killing-it-simple-bash-script

this worked

#!/bin/bash

cmd=$1
seconds=$2

echo "Executing: ${cmd} for $seconds seconds"
$cmd&

cmdpid=$!
sleep $seconds

if [ -d /proc/$cmdpid ]
then
echo "terminating program PID:$cmdpid"
kill $cmdpid
fi
Arian
  • 339
  • This is brilliant but I'm wondering if it is necessary ... there are other commands that can do the same and time out on their own – Mike Q May 12 '18 at 17:41