-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
110 lines (90 loc) · 2.87 KB
/
app.py
File metadata and controls
110 lines (90 loc) · 2.87 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# -*- coding: utf-8 -*-
# pylint: disable=locally-disabled, multiple-statements
# pylint: disable=fixme, line-too-long, invalid-name
# pylint: disable=W0703
""" ClouDNS updater script for container format. App file. """
__author__ = 'EA1HET'
__date__ = "27/12/2019"
import socket
import requests
import settings
from sys import exit
from time import sleep
from datetime import datetime
try:
url_cdns = settings.Config.url_cdns
url_ipio = settings.Config.url_ipio
log_file = settings.Config.log_file
hostname = settings.Config.hostname
sleeptime = settings.Config.sleeptime
except Exception as e:
print('Unexpected: %s' % e)
exit(1)
def read_ip_from_log_file():
"""
Reads log file and gets last IP address logged. In case there's no IP to get, a symbolic
IP address is returned (0.0.0.0) to force a ClouDNS request for update.
:param: None.
:return: An IP address, as string.
"""
try:
with open(log_file, 'a+') as f:
lines = f.read().splitlines()
if not lines:
lastline_ip = '0.0.0.0'
return lastline_ip
else:
lastline_ip = lines[-1]
return lastline_ip[27:]
except Exception as e:
print('Error %s' % e)
exit(1)
def check_actual_ip(i):
"""
Check current apparent IP address and writes log with it.
:param: A counter to print nice information traces in stdout.
:return: An IP address, as string.
"""
resp = requests.get(url=url_ipio).json()
linea_log = str(datetime.utcnow().isoformat(timespec='seconds') + ' (UTC): ' + resp['ip'])
with open(log_file, 'a') as f:
f.write(linea_log + '\r\n')
print(linea_log + ' (# %s) ' % i)
return resp['ip']
def update_ip(ip):
"""
CloudDNS update request via HTTP API call, only if local IP and IP on ClouDNS are different.
:param: An IP address, as string.
:return: None.
"""
ip_in_cdns = socket.gethostbyname(hostname)
if ip_in_cdns == ip:
print('Update: Actual IP is the same than ClouDNS. ClouDNS update call not executed.')
else:
try:
requests.get(url=url_cdns, timeout=(2, 10))
print('Update: IP updated in ClouDNS')
except Exception as e:
print('Error %s' % e)
exit(1)
def main():
counter = 0
while True:
try:
counter += 1
ip_prev = read_ip_from_log_file()
ip_now = check_actual_ip(counter)
if ip_prev != ip_now:
update_ip(ip_now)
except Exception as e:
print('Error %s' % e)
try:
sleep(sleeptime)
except KeyboardInterrupt:
print('Manually stopped the program.')
exit(1)
except Exception as e:
print('Error %s' % e)
exit(1)
if __name__ == '__main__':
main()