开发者

Inform me when site (server) is online again

开发者 https://www.devze.com 2022-12-26 03:48 出处:网络
When I ping one site it returns \"Request timed out\". I want to make little program that will inform me (sound beep or something like that) when this server is online again. No matter in which langua

When I ping one site it returns "Request timed out". I want to make little program that will inform me (sound beep or something like that) when this server is online again. No matter in which language. I think it should 开发者_如何学JAVAbe very simple script with a several lines of code. So how to write it?


Some implementations of ping allow you to specify conditions for exiting after receipt of packets:

On Mac OS X, use ping -a -o $the_host

  • ping will keep trying (by default)
  • -a means beep when a packet is received
  • -o means exit when a packet is received

On Linux (Ubuntu at least), use ping -a -c 1 -w inf $the_host

  • -a means beep when a packet is received
  • -c 1 specifies the number of packets to send before exit (in this case 1)
  • -w inf specifies the deadline for when ping exits no matter what (in this case Infinite)
  • when -c and -w are used together, -c becomes number of packets received before exit

Either can be chained to perform your next command, e.g. to ssh into the server as soon as it comes up (with a gap between to allow sshd to actually start up):

# ping -a -o $the_host && sleep 3 && ssh $the_host


Don't forget the notify sound like echo"^G"! Just to be different - here's Windows batch:

C:\> more pingnotify.bat
:AGAIN
ping -n 1 %1%
IF ERRORLEVEL 1 GOTO AGAIN
sndrec32 /play /close "C:\Windows\Media\Notify.wav"

C:\> pingnotify.bat localhost

:)


One way is to run ping is a loop, e.g.

while ! ping -c 1 host; do sleep 1; done

(You can redirect the output to /dev/null if you want to keep it quiet.)

On some systems, such as Mac OS X, ping may also have the options -a -o (as per another answer) available which will cause it to keep pinging until a response is received. However, the ping on many (most?) Linux systems does not have the -o option and the kind of equivalent -c 1 -w 0 still exits if the network returns an error.

Edit: If the host does not respond to ping or you need to check the availability of service on a certain port, you can use netcat in the zero I/O mode:

while ! nc -w 5 -z host port; do sleep 1; done

The -w 5 specifies a 5 second timeout for each individual attempt. Note that with netcat you can even list multiple ports (or port ranges) to scan when some of them becomes available.

Edit 2: The loops shown above keep trying until the host (or port) is reached. Add your alert command after them, e.g. beep or pop-up a window.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号