Compare commits

...

38 Commits
0.4 ... main

Author SHA1 Message Date
40c4476081 Quick fix 2023-04-17 11:02:08 +02:00
890dfea5ab Quick fix 2023-04-17 10:55:01 +02:00
f39ca9c997 Merge branch 'main' of https://gitlab.pm/rune/ddns 2023-04-17 10:35:04 +02:00
099499f4c6 Fixed longer domain names for local add of existing domains 2023-04-17 10:34:57 +02:00
c6bdca6562 Type fix 2023-04-16 18:45:19 +02:00
b436703b29 Typo fix 2023-04-16 18:34:20 +02:00
6beea36361 Update version .1 2023-04-15 17:12:43 +02:00
024211f0f3 Fix issue #1 2023-04-15 17:11:35 +02:00
15a6540372 Merge branch 'main' of https://gitlab.pm/rune/ddns 2023-04-05 10:45:18 +02:00
60bb9d6119 Added feature. Fixed bugs. Fixed typos 2023-04-05 10:44:00 +02:00
ee2a1cb6df Update 'README.md' 2023-04-03 14:29:37 +02:00
d98ed44ba9 Bump version# 2023-03-29 09:10:27 +02:00
678c32b2ea Fixed an error when adding sub domains already in DO DNS 2023-03-29 09:08:08 +02:00
5ccb9b90d4 Missed a small issue 2023-03-28 12:27:35 +02:00
4a1ac2ec6e Missed a small issue 2023-03-28 12:23:09 +02:00
29aec3b030 Added created date for new domains 2023-03-28 12:16:45 +02:00
ebe9ff1860 Added created date for new domains 2023-03-28 12:12:04 +02:00
d271c44adf Fixed bug in SQL for adding new subdomain 2023-03-28 11:41:06 +02:00
7380175ba0 Added some more logging. Small fixes 2023-03-23 17:42:15 +01:00
f543eea7e5 Small fixes 2023-03-22 12:28:14 +01:00
5f675974cb Small fixes 2023-03-22 12:19:45 +01:00
3a3c908f0a Small fixes 2023-03-22 12:17:12 +01:00
ea37dc4d74 Small fixes 2023-03-22 12:15:40 +01:00
604ed4290c Small fixes 2023-03-22 12:13:38 +01:00
35b05c169d Small fixes 2023-03-22 12:10:40 +01:00
0b1dd9c2c7 Small fixes 2023-03-22 12:08:08 +01:00
ca30ffea95 Small fixes 2023-03-22 11:58:38 +01:00
b3fd3e2a3e Small fixes 2023-03-22 11:55:58 +01:00
72fe8ee958 Small fixes 2023-03-22 11:54:00 +01:00
0de69168af Small fixes 2023-03-22 11:51:30 +01:00
f9b81db550 Small fixes 2023-03-22 11:48:56 +01:00
6b67acac4d Small fixes 2023-03-22 11:47:47 +01:00
ebffbf24d3 Small fixes 2023-03-22 11:47:12 +01:00
32e0437011 Small fixes 2023-03-22 11:45:06 +01:00
a6fa35171f Small fixes 2023-03-22 11:42:21 +01:00
009d86ba28 Small fixes 2023-03-22 11:39:35 +01:00
87f6d39ee6 Small fixes 2023-03-22 11:36:59 +01:00
d8994503da Small fixes 2023-03-22 11:36:11 +01:00
3 changed files with 204 additions and 114 deletions

View File

@ -4,13 +4,7 @@ _DDNS_ is a dynamic DNS helper for Digital Ocean users to utilize their DO accou
## Installation ## Installation
Install with Download the latest relase from https://gitlab.pm/rune/ddns/releases. Unzip and move to a folder in you path (ease of use). You can also rename the file ```ddns.py``` to just ```ddns``` and make the file executable with ```chmod +x ddns```. To install required python modules run ```pip3 install -r requirements.txt```
```
wget -O - https://gitlab.pm/rune/test/raw/branch/main/setup.sh | bash
```
#### Manual install
Download the latest relase from https://gitlab.pm/rune/ddns/releases. Unzip and move to a folder in you path (ease of use). You can alos rename the file ```ddns.py``` to just ```ddns``` and make the file executable with ```chmod +x ddns```
## Usage ## Usage
@ -33,7 +27,7 @@ to discuss what you would like to change.
## Support ## Support
If you found a bug or you have sugestion for new features create an issue. If you found a bug or you have suggestion for new features create an issue.
## Future development ## Future development

238
ddns.py
View File

@ -18,8 +18,8 @@ homefilepath = Path.home()
filepath = homefilepath.joinpath('.config/ddns') filepath = homefilepath.joinpath('.config/ddns')
database = filepath.joinpath('ddns.db') database = filepath.joinpath('ddns.db')
logfile = filepath.joinpath('ddns.log') logfile = filepath.joinpath('ddns.log')
logging.basicConfig(filename=logfile,level=logging.INFO) logging.basicConfig(filename=logfile,level=logging.INFO,format='%(message)s')
app_version = '0.4' app_version = '0.5.2'
def get_ip(): def get_ip():
@ -35,6 +35,7 @@ def get_ip():
return current_ip return current_ip
except Exception as e: except Exception as e:
error = str(e) error = str(e)
logging.error(time.strftime("%Y-%m-%d %H:%M") + ' - Error : ' + str(e))
return error return error
else: else:
return None return None
@ -47,7 +48,7 @@ def connect_database():
try: try:
conn = sqlite3.connect(database) conn = sqlite3.connect(database)
except Error as e: except Error as e:
logging.error(time.strftime("%Y-%m-%d %H:%M")+' - Error : ' + str(e)) logging.error(time.strftime("%Y-%m-%d %H:%M") + ' - Error : ' + str(e))
print(e) print(e)
finally: finally:
if conn: if conn:
@ -90,9 +91,11 @@ def api(api_value):
count = cursor.fetchone()[0] count = cursor.fetchone()[0]
if count == 0: if count == 0:
cursor.execute('INSERT INTO apikey values(?,?)', (1, api_value)) cursor.execute('INSERT INTO apikey values(?,?)', (1, api_value))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : API key added')
print('Your API key has been added.') print('Your API key has been added.')
else: else:
cursor.execute('UPDATE apikey SET api = ? WHERE id = 1',(api_value,)) cursor.execute('UPDATE apikey SET api = ? WHERE id = 1',(api_value,))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : API key updated')
print('Your API key has been updated.') print('Your API key has been updated.')
conn.commit() conn.commit()
@ -115,15 +118,21 @@ def add_domian(domain):
else: else:
cursor.execute('INSERT INTO domains values(?,?)', (None, domain,)) cursor.execute('INSERT INTO domains values(?,?)', (None, domain,))
print('The domain [b]%s[/b] has been added to the DB' % (domain)) print('The domain [b]%s[/b] has been added to the DB' % (domain))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Domain %s added' %(domain))
conn.commit() conn.commit()
def add_subdomain(domain): def add_subdomain(domain):
if set(domain).difference(ascii_letters + '.' + digits): now = datetime.now().strftime("%Y-%m-%d %H:%M")
if set(domain).difference(ascii_letters + '.' + digits + '-' + '@'):
print('[red]Error:[/red] Give the domain name in simple form e.g. [b]test.domain.com[/b]') print('[red]Error:[/red] Give the domain name in simple form e.g. [b]test.domain.com[/b]')
else: else:
parts = domain.split('.') parts = domain.split('.')
if len(parts) > 3:
top = parts[1] + '.' + parts[2] + '.' + parts[3]
sub = parts[0]
else:
sub = parts[0] sub = parts[0]
top = parts[1] + '.' + parts[2] top = parts[1] + '.' + parts[2]
apikey = get_api() apikey = get_api()
@ -140,9 +149,10 @@ def add_subdomain(domain):
if count == 0: if count == 0:
print('[red]Error:[/red] Top domain [bold]%s[/bold] does not exist in the DB. Please add it with [i]ddns -t %s[/i].' % (top,top)) print('[red]Error:[/red] Top domain [bold]%s[/bold] does not exist in the DB. Please add it with [i]ddns -t %s[/i].' % (top,top))
else: else:
cursor.execute('SELECT id FROM domains WHERE name LIKE ?',(top,)) cursor.execute('SELECT id,name FROM domains WHERE name LIKE ?',(top,))
topdomain_id = cursor.fetchone() topdomain = cursor.fetchone()
topdomain_id = topdomain_id[0] topdomain_id = topdomain[0]
topdomain_name = topdomain[1]
cursor.execute('SELECT count(*) FROM subdomains WHERE main_id LIKE ? AND name like ?',(topdomain_id,sub,)) cursor.execute('SELECT count(*) FROM subdomains WHERE main_id LIKE ? AND name like ?',(topdomain_id,sub,))
count = cursor.fetchone()[0] count = cursor.fetchone()[0]
if count != 0: if count != 0:
@ -156,27 +166,33 @@ def add_subdomain(domain):
if response != 'Fail': if response != 'Fail':
response_data = response.json() response_data = response.json()
domainid = str(response_data['domain_record']['id']) domainid = str(response_data['domain_record']['id'])
cursor.execute('INSERT INTO subdomains values(?,?,?,?,?)',(domainid,topdomain_id,sub,ip,None,)) cursor.execute('INSERT INTO subdomains values(?,?,?,?,?,?,?,?,?)',(domainid,topdomain_id,sub,ip,None,now,now,now,1,))
conn.commit() conn.commit()
print('The domain %s has been added.' % (domain)) print('The domain %s has been added.' % (domain))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : subdomain %s added'%(domain))
else: else:
return '[red]Error: %s [/red]' % (str(response)) return '[red]Error: %s [/red]' % (str(response))
def remove_subdomain(domain): def remove_subdomain(domain):
if set(domain).difference(ascii_letters + '.' + digits): if set(domain).difference(ascii_letters + '.' + digits + '-' + '@'):
print('[red]Error:[/red] Give the domain name in simple form e.g. [b]test.domain.com[/b]') print('[red]Error:[/red] Give the domain name in simple form e.g. [b]test.domain.com[/b]')
else: else:
parts = domain.split('.') parts = domain.split('.')
if len(parts) > 3:
top = parts[1] + '.' + parts[2] + '.' + parts[3]
sub = parts[0]
else:
sub = parts[0] sub = parts[0]
top = parts[1] + '.' + parts[2] top = parts[1] + '.' + parts[2]
longtop=sub+'.'+top
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM domains WHERE name like ?',(top,)) cursor.execute('SELECT COUNT(*) FROM domains WHERE name like ? or name like ?',(top,longtop,))
count = cursor.fetchone()[0] count = cursor.fetchone()[0]
if count == 0: if count == 0:
print('[red]Error:[/red] Top domain [bold]%s[/bold] does not exist in the DB. So I\'m giving up!.' % (top)) print('[red]Error:[/red] Top domain [bold]%s[/bold] does not exist in the DB. So I\'m giving up!.' % (top))
else: else:
cursor.execute('SELECT COUNT(*) FROM subdomains WHERE name like ? and main_id=(SELECT id from domains WHERE name=?)',(sub,top,)) cursor.execute('SELECT COUNT(*) FROM subdomains WHERE name like ? and main_id=(SELECT id from domains WHERE name like ? or name like ?)',(sub,top,longtop,))
count = cursor.fetchone()[0] count = cursor.fetchone()[0]
if count == 0: if count == 0:
print('[red]Error:[/red] Domain [bold]%s[/bold] does not exist in the DB. So I\'m giving up!.' % (domain)) print('[red]Error:[/red] Domain [bold]%s[/bold] does not exist in the DB. So I\'m giving up!.' % (domain))
@ -185,18 +201,61 @@ def remove_subdomain(domain):
if apikey == None: if apikey == None:
print("[red]Error:[/red] Missing APIkey. Please add one!") print("[red]Error:[/red] Missing APIkey. Please add one!")
else: else:
cursor.execute('SELECT id FROM subdomains WHERE name like ? and main_id=(SELECT id from domains WHERE name=?)',(sub,top,)) cursor.execute('SELECT id FROM subdomains WHERE name like ? and main_id=(SELECT id from domains WHERE name like ? or name like ?)',(sub,top,longtop,))
subdomain_id = str(cursor.fetchone()[0]) subdomain_id = str(cursor.fetchone()[0])
headers = {'Authorization': 'Bearer ' + apikey, "Content-Type": "application/json"} headers = {'Authorization': 'Bearer ' + apikey, "Content-Type": "application/json"}
response = requests.delete('https://api.digitalocean.com/v2/domains/'+top+'/records/' + subdomain_id, headers=headers) response = requests.delete('https://api.digitalocean.com/v2/domains/'+top+'/records/' + subdomain_id, headers=headers)
if str(response) == '<Response [204]>': if str(response) == '<Response [204]>':
cursor.execute('DELETE from subdomains where id=?',(subdomain_id,)) cursor.execute('DELETE from subdomains where id=?',(subdomain_id,))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Subdomain %s removed' %(domain))
conn.commit() conn.commit()
else: else:
print('[red]Error: [/red]An error occurred! Please try again later!') print('[red]Error: [/red]An error occurred! Please try again later!')
def edit_subdomain(domain):
if set(domain).difference(ascii_letters + '.' + digits + '-' + '@'):
print('[red]Error:[/red] Give the domain name in simple form e.g. [b]test.domain.com[/b]')
else:
parts = domain.split('.')
if len(parts) > 3:
top = parts[1] + '.' + parts[2] + '.' + parts[3]
sub = parts[0]
else:
sub = parts[0]
top = parts[1] + '.' + parts[2]
longtop=sub+'.'+top
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM domains WHERE name like ? or name like ?',(top,longtop,))
count = cursor.fetchone()[0]
if count == 0:
print('[red]Error:[/red] Top domain [bold]%s[/bold] does not exist in the DB. So I\'m giving up!.' % (top))
else:
cursor.execute('SELECT COUNT(*) FROM subdomains WHERE name like ? and main_id=(SELECT id from domains WHERE name like ? or name like ?)',(sub,top,longtop))
count = cursor.fetchone()[0]
if count == 0:
print('[red]Error:[/red] Domain [bold]%s[/bold] does not exist in the DB. So I\'m giving up!.' % (domain))
else:
apikey = get_api()
if apikey == None:
print("[red]Error:[/red] Missing APIkey. Please add one!")
else:
cursor.execute('SELECT id,active FROM subdomains WHERE name like ? and main_id=(SELECT id from domains WHERE name like ? or name like ?)',(sub,top,longtop))
domain_info = cursor.fetchone()
subdomain_id = str(domain_info[0])
status = domain_info[1]
if status == 1:
status = 0
else:
status = 1
cursor.execute('UPDATE subdomains SET active = ? WHERE id = ?',(status,subdomain_id,))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Status for domain %s changed' %(domain))
print('Status for domain %s changed' %(domain))
conn.commit()
def show_all_top_domains(): def show_all_top_domains():
cursor = conn.cursor() cursor = conn.cursor()
apikey = get_api() apikey = get_api()
@ -233,8 +292,9 @@ def list_sub_domains(domain):
if count == 0: if count == 0:
print("[red]Error: [/red]No such domain. Check spelling or use ddns -d to show all top domains.") print("[red]Error: [/red]No such domain. Check spelling or use ddns -d to show all top domains.")
else: else:
print('\n\nCurrent sub domains for [b]%s[/b]' % (domain)) print('\n\nCurrent sub domains for [b]%s[/b]\n\n' % (domain))
print('=====================================================================') print('Domain\t\t\t\tCreated\t\t\tUpdated\t\t\tChecked\t\t\tActive')
print('==================================================================================================================')
cursor.execute('SELECT id FROM domains WHERE name LIKE ?', (domain,)) cursor.execute('SELECT id FROM domains WHERE name LIKE ?', (domain,))
topdomain_id = cursor.fetchone()[0] topdomain_id = cursor.fetchone()[0]
cursor.execute('SELECT COUNT(*) FROM subdomains WHERE main_id LIKE ?',(topdomain_id,)) cursor.execute('SELECT COUNT(*) FROM subdomains WHERE main_id LIKE ?',(topdomain_id,))
@ -242,12 +302,16 @@ def list_sub_domains(domain):
if count == 0: if count == 0:
print('[red]Error:[/red] No sub domains for [b]%s[/b]' % (domain)) print('[red]Error:[/red] No sub domains for [b]%s[/b]' % (domain))
else: else:
cursor.execute('SELECT name,last_updated FROM subdomains WHERE main_id LIKE ?',(topdomain_id,) ) cursor.execute('SELECT name,last_updated,last_checked,created,active FROM subdomains WHERE main_id LIKE ?',(topdomain_id,) )
subdomains = cursor.fetchall() subdomains = cursor.fetchall()
for i in subdomains: for i in subdomains:
if i[4] == 1:
active = 'True'
else:
active = 'False'
topdomain = i[0]+'.'+domain topdomain = i[0]+'.'+domain
topdomain = "{:<25}".format(topdomain) topdomain = "{:<25}".format(topdomain)
print(topdomain+'\tLast updated : '+i[1]) print(topdomain+'\t'+i[3]+'\t'+i[1]+'\t'+i[2]+'\t'+active)
print('\n') print('\n')
@ -280,12 +344,17 @@ def domaininfo(domain):
apikey = get_api() apikey = get_api()
local_ip = get_ip() local_ip = get_ip()
cursor = conn.cursor() cursor = conn.cursor()
if set(domain).difference(ascii_letters + '.'): if set(domain).difference(ascii_letters + '.' + digits + '@' + '-'):
print('[red]Error:[/red]. Give the domain name in simple form e.g. [bold]test.domain.com[/bold]') print('[red]Error:[/red]. Give the domain name in simple form e.g. [bold]test.domain.com[/bold]')
else: else:
parts = domain.split('.') parts = domain.split('.')
topdomain = parts[1]+'.'+parts[2] if len(parts) > 3:
cursor.execute('SELECT id FROM domains WHERE name like ?', (topdomain,)) top = parts[1] + '.' + parts[2] + '.' + parts[3]
sub = parts[0]
else:
sub = parts[0]
top = parts[1] + '.' + parts[2]
cursor.execute('SELECT id FROM domains WHERE name like ?', (top,))
domainid = cursor.fetchone()[0] domainid = cursor.fetchone()[0]
cursor.execute('SELECT * FROM subdomains WHERE main_id like ?', (domainid,)) cursor.execute('SELECT * FROM subdomains WHERE main_id like ?', (domainid,))
domains = cursor.fetchall() domains = cursor.fetchall()
@ -307,7 +376,9 @@ def show_current_info():
ipserver = '[red]Error:[/red] No IP resolvers in DB' ipserver = '[red]Error:[/red] No IP resolvers in DB'
else: else:
cursor.execute('SELECT * FROM ipservers') cursor.execute('SELECT * FROM ipservers')
ipserver = cursor.fetchall()[0][1] ipservers = cursor.fetchall()
ip4server = ipservers[0][1]
ip6server = ipservers[0][2]
if API == None: if API == None:
API = '[red]Error:[/red] API key not stored in DB' API = '[red]Error:[/red] API key not stored in DB'
@ -318,11 +389,11 @@ def show_current_info():
subdomains = cursor.fetchone()[0] subdomains = cursor.fetchone()[0]
print('[b]ddns[/b] - a DigitalOcean dynamic DNS solution.') print('\n[b]ddns[/b] - a DigitalOcean dynamic DNS solution.')
print('===================================================') print('===================================================')
print('API key : [b]%s[/b]' % (API)) print('API key : [b]%s[/b]' % (API))
print('IP v4 resolver : [b]%s[/b]' % (ipserver)) print('IP v4 resolver : [b]%s[/b]' % (ip4server))
print('IP v6 resolver : [b]N/A[/b]') print('IP v6 resolver : [b]%s[/b]' % (ip6server))
print('Logfile : [b]%s[/b]' % (logfile)) print('Logfile : [b]%s[/b]' % (logfile))
print('Top domains : [b]%s[/b]' % (topdomains)) print('Top domains : [b]%s[/b]' % (topdomains))
print('sub domains : [b]%s[/b]' % (subdomains)) print('sub domains : [b]%s[/b]' % (subdomains))
@ -344,6 +415,7 @@ def ip_server(ipserver, ip_type):
else: else:
cursor.execute('UPDATE ipservers SET ip4_server = ? WHERE id = 1',(ipserver,)) cursor.execute('UPDATE ipservers SET ip4_server = ? WHERE id = 1',(ipserver,))
print('IP resolver (%s) for ipv%s updated.' % (ipserver, ip_type)) print('IP resolver (%s) for ipv%s updated.' % (ipserver, ip_type))
logging.info(time.strftime("%Y-%m-%d %H:%M")+' - Info : IP resolver (%s) for ipv%s updated.' % (ipserver, ip_type))
conn.commit() conn.commit()
elif ip_type == '6': elif ip_type == '6':
cursor.execute('SELECT COUNT(ip6_server) FROM ipservers') cursor.execute('SELECT COUNT(ip6_server) FROM ipservers')
@ -355,6 +427,7 @@ def ip_server(ipserver, ip_type):
else: else:
cursor.execute('UPDATE ipservers SET ip6_server = ? WHERE id = 1',(ipserver,)) cursor.execute('UPDATE ipservers SET ip6_server = ? WHERE id = 1',(ipserver,))
print('IP resolver (%s) for ipv%s updated. \n\r This IP version is not supported.' % (ipserver, ip_type)) print('IP resolver (%s) for ipv%s updated. \n\r This IP version is not supported.' % (ipserver, ip_type))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : IP resolver (%s) for ipv%s updated.' % (ipserver, ip_type))
conn.commit() conn.commit()
@ -365,18 +438,22 @@ def updateip(force):
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM subdomains') cursor.execute('SELECT COUNT(*) FROM subdomains')
count = cursor.fetchone()[0] count = cursor.fetchone()[0]
now = datetime.now() now = datetime.now().strftime("%d-%m-%Y %H:%M")
updated = None
if count == 0: if count == 0:
print('[red]Error: [/red]There are no dynamic domains active.'\ print('[red]Error: [/red]There are no dynamic domains active.'\
' Start by adding a new domain with [i]ddns -s test.example.com[/i]') ' Start by adding a new domain with [i]ddns -s test.example.com[/i]')
else: else:
cursor.execute('SELECT id FROM subdomains') cursor.execute('SELECT id,active FROM subdomains')
rows = cursor.fetchall() rows = cursor.fetchall()
for i in rows: for i in rows:
cursor.execute('SELECT name FROM domains WHERE id like (SELECT main_id from subdomains WHERE id = ?)',(i[0],)) cursor.execute('SELECT name FROM domains WHERE id like (SELECT main_id from subdomains WHERE id = ?)',(i[0],))
domain_name = str(cursor.fetchone()[0]) domain_info = cursor.fetchone()
domain_name = str(domain_info[0])
domain_status = i[1]
subdomain_id = str(i[0]) subdomain_id = str(i[0])
# Chek if an update is required # Chek if an update is required
if domain_status == 1:
req = urllib.request.Request('https://api.digitalocean.com/v2/domains/' + domain_name + '/records/' + subdomain_id) req = urllib.request.Request('https://api.digitalocean.com/v2/domains/' + domain_name + '/records/' + subdomain_id)
req.add_header('Content-Type', 'application/json') req.add_header('Content-Type', 'application/json')
req.add_header('Authorization', 'Bearer ' + apikey) req.add_header('Authorization', 'Bearer ' + apikey)
@ -384,31 +461,45 @@ def updateip(force):
remote = current.read().decode('utf-8') remote = current.read().decode('utf-8')
remoteData = json.loads(remote) remoteData = json.loads(remote)
remoteIP4 = remoteData['domain_record']['data'] remoteIP4 = remoteData['domain_record']['data']
if remoteIP4 != current_ip or force == True: domainname = str(remoteData['domain_record']['name'])
if remoteIP4 != current_ip or force == True and domain_status == 1:
updated = True
data = {'type': 'A', 'data': current_ip} data = {'type': 'A', 'data': current_ip}
headers = {'Authorization': 'Bearer ' + apikey, "Content-Type": "application/json"} headers = {'Authorization': 'Bearer ' + apikey, "Content-Type": "application/json"}
response = requests.patch('https://api.digitalocean.com/v2/domains/'+domain_name+'/records/' + subdomain_id, data=json.dumps(data), headers=headers) response = requests.patch('https://api.digitalocean.com/v2/domains/'+domain_name+'/records/' + subdomain_id, data=json.dumps(data), headers=headers)
if str(response) != '<Response [200]>': if str(response) != '<Response [200]>':
logging.error(time.strftime("%Y-%m-%d %H:%M")+' - Error : ' + str(response.json)) logging.error(time.strftime("%Y-%m-%d %H:%M")+' - Error updating ('+str(domain_name)+') : ' + str(response.content))
else: else:
cursor.execute('UPDATE subdomains SET current_ip4=? WHERE id = ?',(current_ip,subdomain_id,)) cursor.execute('UPDATE subdomains SET current_ip4=? WHERE id = ?',(current_ip,subdomain_id,))
cursor.execute('UPDATE subdomains SET last_updated=? WHERE id = ?',(now.strftime("%d/%m/%Y %H:%M:%S"),subdomain_id,)) cursor.execute('UPDATE subdomains SET last_updated=? WHERE id = ?',(now,subdomain_id,))
cursor.execute('UPDATE subdomains SET last_checked=? WHERE id = ?',(now,subdomain_id,))
conn.commit() conn.commit()
else: else:
cursor.execute('UPDATE subdomains SET last_checked=? WHERE id = ?',(now.strftime("%d/%m/%Y %H:%M:%S"),subdomain_id,)) cursor.execute('UPDATE subdomains SET last_checked=? WHERE id = ?',(now,subdomain_id,))
conn.commit() conn.commit()
if updated == None:
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : No updated necessary')
else:
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Updates done. Use ddns -l domain.com to check domain')
def local_add_subdomain(domain,domainid): def local_add_subdomain(domain,domainid):
if set(domain).difference(ascii_letters + '.' + digits + '-'): now = datetime.now().strftime("%Y-%m-%d %H:%M")
if set(domain).difference(ascii_letters + '.' + digits + '-' + '@'):
print('[red]Error:[/red] Give the domain name in simple form e.g. [b]test.domain.com[/b]') print('[red]Error:[/red] Give the domain name in simple form e.g. [b]test.domain.com[/b]')
else: else:
parts = domain.split('.') parts = domain.split('.')
if len(parts) > 3:
top = parts[1] + '.' + parts[2] + '.' + parts[3]
sub = parts[0]
else:
sub = parts[0] sub = parts[0]
top = parts[1] + '.' + parts[2] top = parts[1] + '.' + parts[2]
apikey = get_api() apikey = get_api()
longtop=sub+'.'+top
if apikey == None: if apikey == None:
print("[red]Error:[/red] Missing APIkey. Please add one!") print("[red]Error:[/red] Missing APIkey. Please add one!")
else: else:
@ -417,12 +508,12 @@ def local_add_subdomain(domain,domainid):
print('[red]Error:[/red] Failed to get public IP. Do you have a typo in your URI? [red]Error %s.[/red]' % (ip)) print('[red]Error:[/red] Failed to get public IP. Do you have a typo in your URI? [red]Error %s.[/red]' % (ip))
else: else:
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM domains WHERE name like ?',(top,)) cursor.execute('SELECT COUNT(*) FROM domains WHERE name like ? or name like ?',(top,longtop,))
count = cursor.fetchone()[0] count = cursor.fetchone()[0]
if count == 0: if count == 0:
print('[red]Error:[/red] Top domain [bold]%s[/bold] does not exist in the DB. Please add it with [i]ddns -t %s[/i].' % (top,top)) print('[red]Error:[/red] Top domain [bold]%s[/bold] does not exist in the DB. Please add it with [i]ddns -t %s[/i].' % (top,top))
else: else:
cursor.execute('SELECT id FROM domains WHERE name LIKE ?',(top,)) cursor.execute('SELECT id FROM domains WHERE name LIKE ? or name like ?',(top,longtop,))
topdomain_id = cursor.fetchone() topdomain_id = cursor.fetchone()
topdomain_id = topdomain_id[0] topdomain_id = topdomain_id[0]
cursor.execute('SELECT count(*) FROM subdomains WHERE main_id LIKE ? AND name like ?',(topdomain_id,sub,)) cursor.execute('SELECT count(*) FROM subdomains WHERE main_id LIKE ? AND name like ?',(topdomain_id,sub,))
@ -430,76 +521,108 @@ def local_add_subdomain(domain,domainid):
if count != 0: if count != 0:
print('[red]Error:[/red] [bold]%s[/bold] already exists.' % (domain)) print('[red]Error:[/red] [bold]%s[/bold] already exists.' % (domain))
else: else:
cursor.execute('INSERT INTO subdomains values(?,?,?,?,?)',(domainid,topdomain_id,sub,ip,None,)) cursor.execute('INSERT INTO subdomains values(?,?,?,?,?,?,?,?,?)',(domainid,topdomain_id,sub,ip,None,now,now,now,1,))
conn.commit() conn.commit()
print('The domain %s has been added.' % (domain)) print('The domain %s has been added.' % (domain))
def show_log():
log_file = open(logfile, 'r')
content = log_file.read()
print(content)
log_file.close()
def updatedb(): def updatedb():
# Update DB with new column 20.03.23 # Update DB with new column 20.03.23
# Add last updated field for subdomains # Add last updated field for subdomains
new_table = 'last_updated' new_column = 'last_updated'
info = conn.execute("PRAGMA table_info('subdomains')").fetchall() info = conn.execute("PRAGMA table_info('subdomains')").fetchall()
if not any(new_table in word for word in info): if not any(new_column in word for word in info):
add_column = "ALTER TABLE subdomains ADD COLUMN last_updated text default 'N/A'" add_column = "ALTER TABLE subdomains ADD COLUMN last_updated text default 'N/A'"
conn.execute(add_column) conn.execute(add_column)
conn.commit() conn.commit()
logging.info(time.strftime("%Y-%m-%d %H:%M")+' - Info : Database updated')
new_table = 'last_checked' new_column = 'last_checked'
info = conn.execute("PRAGMA table_info('subdomains')").fetchall() info = conn.execute("PRAGMA table_info('subdomains')").fetchall()
if not any(new_table in word for word in info): if not any(new_column in word for word in info):
add_column = "ALTER TABLE subdomains ADD COLUMN last_checked text default 'N/A'" add_column = "ALTER TABLE subdomains ADD COLUMN last_checked text default 'N/A'"
conn.execute(add_column) conn.execute(add_column)
conn.commit() conn.commit()
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Database updated')
new_column = 'created'
info = conn.execute("PRAGMA table_info('subdomains')").fetchall()
if not any(new_column in word for word in info):
add_column = "ALTER TABLE subdomains ADD COLUMN created text default '[b]Unknown Info[/b]'"
conn.execute(add_column)
conn.commit()
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Database updated')
new_column = 'active'
info = conn.execute("PRAGMA table_info('subdomains')").fetchall()
if not any(new_column in word for word in info):
add_column = "ALTER TABLE subdomains ADD COLUMN active integer default 1"
conn.execute(add_column)
conn.commit()
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Database updated')
# Commandline arguments # Commandline arguments
conn = connect_database() conn = connect_database()
updatedb() updatedb()
parser = argparse.ArgumentParser(prog='ddns', parser = argparse.ArgumentParser(prog='ddns',
description='Application to use domains from DigitalOcean account as dynamic '\ description='Application to use domains from DigitalOcean account as dynamic '\
'DNS domain(s).\nThe app only supports IP4. IPv6 is planned for a later release!'\ 'DNS domain(s).\nThe app only supports IP4. IPv6 is planned for a later release!'\
'\nYou\'ll always find the latest version on https://gitlab.pm/rune/ddns', '\nYou\'ll always find the latest version on https://gitlab.pm/rune/ddns\n\n'\
'For bugs, suggestions, pull requests visit https://gitlab.pm/rune/ddns/issues',
formatter_class=RawTextHelpFormatter, formatter_class=RawTextHelpFormatter,
epilog='Making Selfhosting easier...') epilog='Making Selfhosting easier...')
parser.add_argument('-a', '--api', help='Add/Change API key.', parser.add_argument('-a', '--api', help='Add/Change API key.\n\n',
nargs=1, metavar=('APIkey'), required=False, action="append") nargs=1, metavar=('APIkey'), required=False, action="append")
parser.add_argument('-f', '--force', help='Force update of IP address for all domains.', parser.add_argument('-f', '--force', help='Force update of IP address for all domains.\n\n',
required=False, action="store_true") required=False, action="store_true")
parser.add_argument('-l', '--list', help='List subdomains for supplied domain.', parser.add_argument('-l', '--list', help='List subdomains for supplied domain.\n\n',
nargs=1, metavar=('domain'), required=False, action="append") nargs=1, metavar=('domain'), required=False, action="append")
parser.add_argument('-o', '--serverdomains', help='List subdomains for supplied domain not in ddns DB.', parser.add_argument('-o', '--serverdomains', help='List subdomains for supplied domain not in ddns DB.\n\n',
nargs=1, metavar=('domain'), required=False, action="append") nargs=1, metavar=('domain'), required=False, action="append")
parser.add_argument('-d', '--domains', help='List top domains in your DigitalOcean account.', parser.add_argument('-d', '--domains', help='List top domains in your DigitalOcean account.\n\n',
required=False, action="store_true") required=False, action="store_true")
parser.add_argument('-c', '--current', help='List the current IP address for the sub-domain given', parser.add_argument('-c', '--current', help='List the current IP address for the sub-domain given\n\n',
required=False, nargs=1, action="append") required=False, nargs=1, action="append")
parser.add_argument('-t', '--top', help='Add a new domain from your DigitalOcean account to use as a dynamic DNS domain', parser.add_argument('-t', '--top', help='Add a new domain from your DigitalOcean account to use as a dynamic DNS domain\n\n',
required=False, nargs=1, metavar=('domain'), action='append') required=False, nargs=1, metavar=('domain'), action='append')
parser.add_argument('-s', '--sub', help='Add a new subdomain to your DigitalOcean account and use as dynamic DNS.\n', parser.add_argument('-s', '--sub', help='Add a new subdomain to your DigitalOcean account and use as dynamic DNS.\n\n\n',
required=False, nargs=1, metavar=('domain'), action='append') required=False, nargs=1, metavar=('domain'), action='append')
parser.add_argument('-k', '--local', help='Add an existing DigitalOcean subdomain to your ddns DB and use as dynamic DNS.', parser.add_argument('-k', '--local', help='Add an existing DigitalOcean subdomain to your ddns DB and use as dynamic DNS.\n\n',
required=False, nargs=2, metavar=('domain','domainid'), action='append') required=False, nargs=2, metavar=('domain','domainid'), action='append')
parser.add_argument('-r', '--remove', help='Remove a subdomain from your DigitalOcean account and ddns.', parser.add_argument('-r', '--remove', help='Remove a subdomain from your DigitalOcean account and ddns.\n\n',
required=False, nargs=1, metavar=('domain'), action='append') required=False, nargs=1, metavar=('domain'), action='append')
parser.add_argument('-v', '--version', help='Show current version and config info', parser.add_argument('-v', '--version', help='Show current version and config info\n\n',
required=False, action='store_true') required=False, action='store_true')
parser.add_argument('-p', '--ipserver', help='Set IP server lookup to use. Indicate 4 or 6 for IP type.', parser.add_argument('-q', '--log', help=argparse.SUPPRESS, required=False, action='store_true')
parser.add_argument('-p', '--ipserver', help='Sets or updates IP server lookup to use. Indicate 4 or 6 for IP type.\n\n',
required=False, nargs=2, metavar=('ip4.iurl.no', '4'), action="append") required=False, nargs=2, metavar=('ip4.iurl.no', '4'), action="append")
parser.add_argument('-e', '--edit', help='Changes domain from active to inactive or the other way around...',
required=False, nargs=1, metavar=('test.example.com'), action="append")
args = vars(parser.parse_args()) args = vars(parser.parse_args())
if args['list']: if args['list']:
@ -518,23 +641,18 @@ elif args['version']:
show_current_info() show_current_info()
elif args['force']: elif args['force']:
updateip(True) updateip(True)
elif args['log']:
show_log()
elif args['ipserver']: elif args['ipserver']:
ip_server(args['ipserver'][0][0],args['ipserver'][0][1]) ip_server(args['ipserver'][0][0],args['ipserver'][0][1])
elif args['api']: elif args['api']:
api(args['api'][0][0]) api(args['api'][0][0])
elif args['remove']: elif args['remove']:
remove_subdomain(args['remove'][0][0]) remove_subdomain(args['remove'][0][0])
elif args['edit']:
edit_subdomain(args['edit'][0][0])
elif args['local']: elif args['local']:
local_add_subdomain(args['local'][0][0],args['local'][0][1]) local_add_subdomain(args['local'][0][0],args['local'][0][1])
else: else:
updateip(None) updateip(None)

View File

@ -1,22 +0,0 @@
#!/bin/bash
#
# Install script for Digital Ocean ddns script. You can also do this manually.
# Check https://gitlab.pm/rune/ddns
#
# GPLv3 Rune Olsen (https://blog.rune.pm) 2023
#
wget https://gitlab.pm/rune/ddns/src/branch/main/src/do-ddns/ddns.py
wget https://gitlab.pm/rune/ddns/src/branch/main/src/do-ddns/requirements.txt
echo "ddns downloaded. Moving to /usr/local/bin and setting execute (run) rights on app."
echo "Your computer will ask for password since the rest of the install is done with sudo."
read -n1 -s -r -p $'Press space to continue or any other key to cancle\n' key
if [ "$key" = ' ' ]; then
sudo mv ddns.py /usr/local/bin/ddns
sudo chmod +x /usr/local/bin/ddns
python3 pip3 -r requirements.txt
exit 0
else
echo "Install aborted by user!"
exit 1
fi