Compare commits
28 Commits
0.4
...
ee2a1cb6df
Author | SHA1 | Date | |
---|---|---|---|
ee2a1cb6df | |||
d98ed44ba9 | |||
678c32b2ea | |||
5ccb9b90d4 | |||
4a1ac2ec6e | |||
29aec3b030 | |||
ebe9ff1860 | |||
d271c44adf | |||
7380175ba0 | |||
f543eea7e5 | |||
5f675974cb | |||
3a3c908f0a | |||
ea37dc4d74 | |||
604ed4290c | |||
35b05c169d | |||
0b1dd9c2c7 | |||
ca30ffea95 | |||
b3fd3e2a3e | |||
72fe8ee958 | |||
0de69168af | |||
f9b81db550 | |||
6b67acac4d | |||
ebffbf24d3 | |||
32e0437011 | |||
a6fa35171f | |||
009d86ba28 | |||
87f6d39ee6 | |||
d8994503da |
@@ -4,13 +4,7 @@ _DDNS_ is a dynamic DNS helper for Digital Ocean users to utilize their DO accou
|
||||
|
||||
## Installation
|
||||
|
||||
Install with
|
||||
```
|
||||
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```
|
||||
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```. To install required python modules run ```pip3 install -r requirements.txt```
|
||||
|
||||
## Usage
|
||||
|
||||
|
91
ddns.py
91
ddns.py
@@ -19,7 +19,7 @@ filepath = homefilepath.joinpath('.config/ddns')
|
||||
database = filepath.joinpath('ddns.db')
|
||||
logfile = filepath.joinpath('ddns.log')
|
||||
logging.basicConfig(filename=logfile,level=logging.INFO)
|
||||
app_version = '0.4'
|
||||
app_version = '0.4.2.1'
|
||||
|
||||
|
||||
def get_ip():
|
||||
@@ -35,6 +35,7 @@ def get_ip():
|
||||
return current_ip
|
||||
except Exception as e:
|
||||
error = str(e)
|
||||
logging.error(time.strftime("%Y-%m-%d %H:%M") + ' - Error : ' + str(e))
|
||||
return error
|
||||
else:
|
||||
return None
|
||||
@@ -47,7 +48,7 @@ def connect_database():
|
||||
try:
|
||||
conn = sqlite3.connect(database)
|
||||
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)
|
||||
finally:
|
||||
if conn:
|
||||
@@ -90,9 +91,11 @@ def api(api_value):
|
||||
count = cursor.fetchone()[0]
|
||||
if count == 0:
|
||||
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.')
|
||||
else:
|
||||
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.')
|
||||
conn.commit()
|
||||
|
||||
@@ -115,11 +118,13 @@ def add_domian(domain):
|
||||
else:
|
||||
cursor.execute('INSERT INTO domains values(?,?)', (None, 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()
|
||||
|
||||
|
||||
|
||||
def add_subdomain(domain):
|
||||
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]')
|
||||
else:
|
||||
@@ -156,9 +161,10 @@ def add_subdomain(domain):
|
||||
if response != 'Fail':
|
||||
response_data = response.json()
|
||||
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,))
|
||||
conn.commit()
|
||||
print('The domain %s has been added.' % (domain))
|
||||
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : subdomain %s added'%(domain))
|
||||
else:
|
||||
return '[red]Error: %s [/red]' % (str(response))
|
||||
|
||||
@@ -191,6 +197,7 @@ def remove_subdomain(domain):
|
||||
response = requests.delete('https://api.digitalocean.com/v2/domains/'+top+'/records/' + subdomain_id, headers=headers)
|
||||
if str(response) == '<Response [204]>':
|
||||
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()
|
||||
else:
|
||||
print('[red]Error: [/red]An error occurred! Please try again later!')
|
||||
@@ -233,8 +240,9 @@ def list_sub_domains(domain):
|
||||
if count == 0:
|
||||
print("[red]Error: [/red]No such domain. Check spelling or use ddns -d to show all top domains.")
|
||||
else:
|
||||
print('\n\nCurrent sub domains for [b]%s[/b]' % (domain))
|
||||
print('=====================================================================')
|
||||
print('\n\nCurrent sub domains for [b]%s[/b]\n\n' % (domain))
|
||||
print('Domain\t\t\t\tCreated\t\t\tUpdated\t\t\tChecked')
|
||||
print('===============================================================================================')
|
||||
cursor.execute('SELECT id FROM domains WHERE name LIKE ?', (domain,))
|
||||
topdomain_id = cursor.fetchone()[0]
|
||||
cursor.execute('SELECT COUNT(*) FROM subdomains WHERE main_id LIKE ?',(topdomain_id,))
|
||||
@@ -242,12 +250,12 @@ def list_sub_domains(domain):
|
||||
if count == 0:
|
||||
print('[red]Error:[/red] No sub domains for [b]%s[/b]' % (domain))
|
||||
else:
|
||||
cursor.execute('SELECT name,last_updated FROM subdomains WHERE main_id LIKE ?',(topdomain_id,) )
|
||||
cursor.execute('SELECT name,last_updated,last_checked,created FROM subdomains WHERE main_id LIKE ?',(topdomain_id,) )
|
||||
subdomains = cursor.fetchall()
|
||||
for i in subdomains:
|
||||
topdomain = i[0]+'.'+domain
|
||||
topdomain = "{:<25}".format(topdomain)
|
||||
print(topdomain+'\tLast updated : '+i[1])
|
||||
print(topdomain+'\t'+i[3]+'\t'+i[1]+'\t'+i[2])
|
||||
print('\n')
|
||||
|
||||
|
||||
@@ -307,7 +315,9 @@ def show_current_info():
|
||||
ipserver = '[red]Error:[/red] No IP resolvers in DB'
|
||||
else:
|
||||
cursor.execute('SELECT * FROM ipservers')
|
||||
ipserver = cursor.fetchall()[0][1]
|
||||
ipservers = cursor.fetchall()
|
||||
ip4server = ipservers[0][1]
|
||||
ip6server = ipservers[0][2]
|
||||
|
||||
if API == None:
|
||||
API = '[red]Error:[/red] API key not stored in DB'
|
||||
@@ -318,11 +328,11 @@ def show_current_info():
|
||||
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('API key : [b]%s[/b]' % (API))
|
||||
print('IP v4 resolver : [b]%s[/b]' % (ipserver))
|
||||
print('IP v6 resolver : [b]N/A[/b]')
|
||||
print('IP v4 resolver : [b]%s[/b]' % (ip4server))
|
||||
print('IP v6 resolver : [b]%s[/b]' % (ip6server))
|
||||
print('Logfile : [b]%s[/b]' % (logfile))
|
||||
print('Top domains : [b]%s[/b]' % (topdomains))
|
||||
print('sub domains : [b]%s[/b]' % (subdomains))
|
||||
@@ -344,6 +354,7 @@ def ip_server(ipserver, ip_type):
|
||||
else:
|
||||
cursor.execute('UPDATE ipservers SET ip4_server = ? WHERE id = 1',(ipserver,))
|
||||
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()
|
||||
elif ip_type == '6':
|
||||
cursor.execute('SELECT COUNT(ip6_server) FROM ipservers')
|
||||
@@ -355,6 +366,7 @@ def ip_server(ipserver, ip_type):
|
||||
else:
|
||||
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))
|
||||
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : IP resolver (%s) for ipv%s updated.' % (ipserver, ip_type))
|
||||
conn.commit()
|
||||
|
||||
|
||||
@@ -365,7 +377,8 @@ def updateip(force):
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('SELECT COUNT(*) FROM subdomains')
|
||||
count = cursor.fetchone()[0]
|
||||
now = datetime.now()
|
||||
now = datetime.now().strftime("%d-%m-%Y %H:%M")
|
||||
updated = None
|
||||
if count == 0:
|
||||
print('[red]Error: [/red]There are no dynamic domains active.'\
|
||||
' Start by adding a new domain with [i]ddns -s test.example.com[/i]')
|
||||
@@ -385,6 +398,7 @@ def updateip(force):
|
||||
remoteData = json.loads(remote)
|
||||
remoteIP4 = remoteData['domain_record']['data']
|
||||
if remoteIP4 != current_ip or force == True:
|
||||
updated = True
|
||||
data = {'type': 'A', 'data': current_ip}
|
||||
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)
|
||||
@@ -392,16 +406,22 @@ def updateip(force):
|
||||
logging.error(time.strftime("%Y-%m-%d %H:%M")+' - Error : ' + str(response.json))
|
||||
else:
|
||||
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()
|
||||
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()
|
||||
|
||||
|
||||
|
||||
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):
|
||||
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]')
|
||||
else:
|
||||
@@ -430,7 +450,7 @@ def local_add_subdomain(domain,domainid):
|
||||
if count != 0:
|
||||
print('[red]Error:[/red] [bold]%s[/bold] already exists.' % (domain))
|
||||
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,))
|
||||
conn.commit()
|
||||
print('The domain %s has been added.' % (domain))
|
||||
|
||||
@@ -439,29 +459,41 @@ def local_add_subdomain(domain,domainid):
|
||||
def updatedb():
|
||||
# Update DB with new column 20.03.23
|
||||
# Add last updated field for subdomains
|
||||
new_table = 'last_updated'
|
||||
new_column = 'last_updated'
|
||||
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'"
|
||||
conn.execute(add_column)
|
||||
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()
|
||||
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'"
|
||||
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')
|
||||
|
||||
|
||||
|
||||
# Commandline arguments
|
||||
conn = connect_database()
|
||||
updatedb()
|
||||
|
||||
parser = argparse.ArgumentParser(prog='ddns',
|
||||
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!'\
|
||||
'\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,
|
||||
epilog='Making Selfhosting easier...')
|
||||
|
||||
@@ -498,7 +530,7 @@ parser.add_argument('-r', '--remove', help='Remove a subdomain from your Digital
|
||||
parser.add_argument('-v', '--version', help='Show current version and config info',
|
||||
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('-p', '--ipserver', help='Sets or updates IP server lookup to use. Indicate 4 or 6 for IP type.',
|
||||
required=False, nargs=2, metavar=('ip4.iurl.no', '4'), action="append")
|
||||
args = vars(parser.parse_args())
|
||||
|
||||
@@ -528,13 +560,4 @@ elif args['local']:
|
||||
local_add_subdomain(args['local'][0][0],args['local'][0][1])
|
||||
else:
|
||||
updateip(None)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
22
setup.sh
22
setup.sh
@@ -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
|
Reference in New Issue
Block a user