Compare commits
No commits in common. "15a6540372608b5f4c3f95a96e05075acfedab89" and "ee2a1cb6df46ed61f04be346fae248587e8500df" have entirely different histories.
15a6540372
...
ee2a1cb6df
159
ddns.py
159
ddns.py
@ -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,format='%(message)s')
|
logging.basicConfig(filename=logfile,level=logging.INFO)
|
||||||
app_version = '0.5'
|
app_version = '0.4.2.1'
|
||||||
|
|
||||||
|
|
||||||
def get_ip():
|
def get_ip():
|
||||||
@ -125,7 +125,7 @@ def add_domian(domain):
|
|||||||
|
|
||||||
def add_subdomain(domain):
|
def add_subdomain(domain):
|
||||||
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||||
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('.')
|
||||||
@ -161,7 +161,7 @@ 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,now,now,now,1,))
|
cursor.execute('INSERT INTO subdomains values(?,?,?,?,?,?,?,?)',(domainid,topdomain_id,sub,ip,None,now,now,now,))
|
||||||
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))
|
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : subdomain %s added'%(domain))
|
||||||
@ -170,7 +170,7 @@ def add_subdomain(domain):
|
|||||||
|
|
||||||
|
|
||||||
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('.')
|
||||||
@ -204,43 +204,6 @@ def remove_subdomain(domain):
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
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('.')
|
|
||||||
sub = parts[0]
|
|
||||||
top = parts[1] + '.' + parts[2]
|
|
||||||
cursor = conn.cursor()
|
|
||||||
cursor.execute('SELECT COUNT(*) FROM domains WHERE name like ?',(top,))
|
|
||||||
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=?)',(sub,top,))
|
|
||||||
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=?)',(sub,top,))
|
|
||||||
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()
|
||||||
@ -278,8 +241,8 @@ def list_sub_domains(domain):
|
|||||||
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]\n\n' % (domain))
|
print('\n\nCurrent sub domains for [b]%s[/b]\n\n' % (domain))
|
||||||
print('Domain\t\t\t\tCreated\t\t\tUpdated\t\t\tChecked\t\t\tActive')
|
print('Domain\t\t\t\tCreated\t\t\tUpdated\t\t\tChecked')
|
||||||
print('==================================================================================================================')
|
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,))
|
||||||
@ -287,16 +250,12 @@ 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,last_checked,created,active 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()
|
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+'\t'+i[3]+'\t'+i[1]+'\t'+i[2]+'\t'+active)
|
print(topdomain+'\t'+i[3]+'\t'+i[1]+'\t'+i[2])
|
||||||
print('\n')
|
print('\n')
|
||||||
|
|
||||||
|
|
||||||
@ -329,7 +288,7 @@ 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 + '.' + digits + '@' + '-'):
|
if set(domain).difference(ascii_letters + '.'):
|
||||||
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('.')
|
||||||
@ -424,39 +383,35 @@ def updateip(force):
|
|||||||
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,active FROM subdomains')
|
cursor.execute('SELECT id 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_info = cursor.fetchone()
|
domain_name = str(cursor.fetchone()[0])
|
||||||
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)
|
current = urllib.request.urlopen(req)
|
||||||
current = urllib.request.urlopen(req)
|
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'])
|
updated = True
|
||||||
if remoteIP4 != current_ip or force == True and domain_status == 1:
|
data = {'type': 'A', 'data': current_ip}
|
||||||
updated = True
|
headers = {'Authorization': 'Bearer ' + apikey, "Content-Type": "application/json"}
|
||||||
data = {'type': 'A', 'data': current_ip}
|
response = requests.patch('https://api.digitalocean.com/v2/domains/'+domain_name+'/records/' + subdomain_id, data=json.dumps(data), headers=headers)
|
||||||
headers = {'Authorization': 'Bearer ' + apikey, "Content-Type": "application/json"}
|
if str(response) != '<Response [200]>':
|
||||||
response = requests.patch('https://api.digitalocean.com/v2/domains/'+domain_name+'/records/' + subdomain_id, data=json.dumps(data), headers=headers)
|
logging.error(time.strftime("%Y-%m-%d %H:%M")+' - Error : ' + str(response.json))
|
||||||
if str(response) != '<Response [200]>':
|
|
||||||
logging.error(time.strftime("%Y-%m-%d %H:%M")+' - Error updating ('+str(domain_name)+') : ' + str(response.content))
|
|
||||||
else:
|
|
||||||
cursor.execute('UPDATE subdomains SET current_ip4=? WHERE id = ?',(current_ip,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:
|
else:
|
||||||
|
cursor.execute('UPDATE subdomains SET current_ip4=? WHERE id = ?',(current_ip,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,))
|
cursor.execute('UPDATE subdomains SET last_checked=? WHERE id = ?',(now,subdomain_id,))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
else:
|
||||||
|
cursor.execute('UPDATE subdomains SET last_checked=? WHERE id = ?',(now,subdomain_id,))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
if updated == None:
|
if updated == None:
|
||||||
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : No updated necessary')
|
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : No updated necessary')
|
||||||
@ -467,7 +422,7 @@ def updateip(force):
|
|||||||
|
|
||||||
def local_add_subdomain(domain,domainid):
|
def local_add_subdomain(domain,domainid):
|
||||||
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
now = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||||
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('.')
|
||||||
@ -495,17 +450,11 @@ 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,now,now,now,1,))
|
cursor.execute('INSERT INTO subdomains values(?,?,?,?,?,?,?,?)',(domainid,topdomain_id,sub,ip,None,now,now,now,))
|
||||||
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
|
||||||
@ -533,14 +482,6 @@ def updatedb():
|
|||||||
conn.execute(add_column)
|
conn.execute(add_column)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : Database updated')
|
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')
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@ -556,47 +497,41 @@ parser = argparse.ArgumentParser(prog='ddns',
|
|||||||
formatter_class=RawTextHelpFormatter,
|
formatter_class=RawTextHelpFormatter,
|
||||||
epilog='Making Selfhosting easier...')
|
epilog='Making Selfhosting easier...')
|
||||||
|
|
||||||
parser.add_argument('-a', '--api', help='Add/Change API key.\n\n',
|
parser.add_argument('-a', '--api', help='Add/Change API key.',
|
||||||
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.\n\n',
|
parser.add_argument('-f', '--force', help='Force update of IP address for all domains.',
|
||||||
required=False, action="store_true")
|
required=False, action="store_true")
|
||||||
|
|
||||||
parser.add_argument('-l', '--list', help='List subdomains for supplied domain.\n\n',
|
parser.add_argument('-l', '--list', help='List subdomains for supplied domain.',
|
||||||
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.\n\n',
|
parser.add_argument('-o', '--serverdomains', help='List subdomains for supplied domain not in ddns DB.',
|
||||||
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.\n\n',
|
parser.add_argument('-d', '--domains', help='List top domains in your DigitalOcean account.',
|
||||||
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\n\n',
|
parser.add_argument('-c', '--current', help='List the current IP address for the sub-domain given',
|
||||||
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\n\n',
|
parser.add_argument('-t', '--top', help='Add a new domain from your DigitalOcean account to use as a dynamic DNS domain',
|
||||||
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\n\n',
|
parser.add_argument('-s', '--sub', help='Add a new subdomain to your DigitalOcean account and use as dynamic DNS.\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.\n\n',
|
parser.add_argument('-k', '--local', help='Add an existing DigitalOcean subdomain to your ddns DB and use as dynamic DNS.',
|
||||||
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.\n\n',
|
parser.add_argument('-r', '--remove', help='Remove a subdomain from your DigitalOcean account and ddns.',
|
||||||
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\n\n',
|
parser.add_argument('-v', '--version', help='Show current version and config info',
|
||||||
required=False, action='store_true')
|
required=False, action='store_true')
|
||||||
|
|
||||||
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.',
|
||||||
|
|
||||||
|
|
||||||
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']:
|
||||||
@ -615,16 +550,12 @@ 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:
|
||||||
|
Loading…
Reference in New Issue
Block a user