This script allows you to wait until specified port is opened on remote server. This can be useful in automation jobs - restarting server, wake on lan etc. It can also be used for monitoring distant service/site.
The main problem that this script solves is that you need to handle two different timeouts when opening probing socket, and it is not described in python documentation. See http://bugs.python.org/issue5293 for more information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | def wait_net_service(server, port, timeout=None):
""" Wait for network service to appear
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
throw unhandled network exception
"""
import socket
import errno
s = socket.socket()
if timeout:
from time import time as now
# time module is needed to calc timeout shared between two exceptions
end = now() + timeout
while True:
try:
if timeout:
next_timeout = end - now()
if next_timeout < 0:
return False
else:
s.settimeout(next_timeout)
s.connect((server, port))
except socket.timeout, err:
# this exception occurs only if timeout is set
if timeout:
return False
except socket.error, err:
# catch timeout exception from underlying network library
# this one is different from socket.timeout
if type(err.args) != tuple or err[0] != errno.ETIMEDOUT:
raise
else:
s.close()
return True
|
Examples:
wait until Samba service running on 139 port is up
wait_net_service("192.168.1.2", 139)
monitoring test if web server is responding (30 seconds timeout)
online = wait_net_service("192.168.1.2", 139, 30)