-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwhen-up.py
executable file
·76 lines (58 loc) · 1.64 KB
/
when-up.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python
import sys
import os
import time
import getopt
import subprocess
DEFAULT_INTERVAL=60
DEFAULT_TIMEOUT=3600
def print_usage():
print "usage: retry.py [options] -- command"
def print_help():
print '''
usage:
retry.py [options] -- command
description:
retry commands until they succeed or timeout
options:
-h: display this message
-a, --address: the IP address to tes
-i, --interval: the interval between attempts in seconds (default 60s)
-t, --timeout: the timeout in seconds (default 3600s)
'''
def parse_args(argv):
interval = DEFAULT_INTERVAL
timeout = DEFAULT_TIMEOUT
address = ""
try:
opts, args = getopt.getopt(argv, "hi:t:a:", ["interval=","timeout=","address="])
except getopt.GetoptError:
print_usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print_help()
sys.exit()
elif opt in ['-a', '--address']:
address = arg
elif opt in ['-i', '--interval']:
interval = arg
elif opt in ['-t', '--timeout']:
timeout = arg
return int(interval), int(timeout), address, args
def is_up(address):
if os.system("ping -c 1 " + address) is 0:
return True
else:
return False
def main():
interval, timeout, address, command = parse_args(sys.argv[1:])
while timeout > 0:
if (is_up(address)):
returncode = subprocess.call(command)
if returncode == 0:
break
time.sleep(interval)
timeout -= interval
if __name__ == "__main__":
main()