Added logging file. Formated some of the outputs

This commit is contained in:
rune 2023-03-20 09:16:06 +01:00
parent 69a842f41d
commit ab8aa7f89f
2 changed files with 43 additions and 23 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
*.zip
*.db
.DS_Store

61
ddns.py
View File

@ -17,7 +17,9 @@ from argparse import RawTextHelpFormatter
homefilepath = Path.home()
filepath = homefilepath.joinpath('.config/ddns')
database = filepath.joinpath('ddns.db')
app_version = '0.2'
logfile = filepath.joinpath('ddns.log')
logging.basicConfig(filename=logfile,level=logging.INFO)
app_version = '0.3'
def get_ip():
@ -239,10 +241,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 FROM subdomains WHERE main_id LIKE ?',(topdomain_id,) )
cursor.execute('SELECT name,last_updated FROM subdomains WHERE main_id LIKE ?',(topdomain_id,) )
subdomains = cursor.fetchall()
for i in subdomains:
print(i[0]+'.'+domain)
topdomain = i[0]+'.'+domain
topdomain = "{:<25}".format(topdomain)
print(topdomain+'\tLast updated : '+i[1])
print('\n')
@ -265,7 +269,7 @@ def list_do_sub_domains(domain):
cursor.execute('SELECT COUNT(*) FROM subdomains WHERE id like ?',(str(k['id']),))
count = cursor.fetchone()[0]
if count == 0:
print(k['name']+'.'+domain+' ID : '+str(k['id']))
print(k['name']+'.'+domain+'\t\tID : '+str(k['id']))
@ -318,6 +322,7 @@ def show_current_info():
print('API key : [b]%s[/b]' % (API))
print('IP v4 resolver : [b]%s[/b]' % (ipserver))
print('IP v6 resolver : [b]N/A[/b]')
print('Logfile : [b]%s[/b]' % (logfile))
print('Top domains : [b]%s[/b]' % (topdomains))
print('sub domains : [b]%s[/b]' % (subdomains))
print('')
@ -353,7 +358,7 @@ def ip_server(ipserver, ip_type):
def updateip():
def updateip(force):
apikey = get_api()
current_ip = get_ip()
cursor = conn.cursor()
@ -370,17 +375,29 @@ def updateip():
cursor.execute('SELECT name FROM domains WHERE id like (SELECT main_id from subdomains WHERE id = ?)',(i[0],))
domain_name = str(cursor.fetchone()[0])
subdomain_id = str(i[0])
data = {'type': 'A', 'data': current_ip}
#print(domain_name, subdomain_id,current_ip,data)
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 = response.json()
if str(response) != '<Response [200]>':
print('[red]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,))
conn.commit()
# Chek if an update is required
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('Authorization', 'Bearer ' + apikey)
current = urllib.request.urlopen(req)
remote = current.read().decode('utf-8')
remoteData = json.loads(remote)
remoteIP4 = remoteData['domain_record']['data']
if force == True:
remoteIP4 = '0.0.0.0'
# Only update domains with outdated IP's
if remoteIP4 != current_ip:
data = {'type': 'A', 'data': current_ip}
#print(domain_name, subdomain_id,current_ip,data)
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 = response.json()
if str(response) != '<Response [200]>':
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,))
conn.commit()
@ -432,7 +449,6 @@ def updatedb():
# Commandline arguments
conn = connect_database()
updatedb()
@ -446,6 +462,9 @@ parser = argparse.ArgumentParser(prog='ddns',
parser.add_argument('-a', '--api', help='Add/Change API key.',
nargs=1, metavar=('APIkey'), required=False, action="append")
parser.add_argument('-f', '--force', help='Force update of IP address for all domains.',
required=False, action="store_true")
parser.add_argument('-l', '--list', help='List subdomains for supplied domain.',
nargs=1, metavar=('domain'), required=False, action="append")
@ -464,7 +483,7 @@ parser.add_argument('-t', '--top', help='Add a new domain from your DigitalOcean
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')
parser.add_argument('-k', '--local', help='Add an existing DigitalOcean domain 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.',
required=False, nargs=2, metavar=('domain','domainid'), action='append')
parser.add_argument('-r', '--remove', help='Remove a subdomain from your DigitalOcean account and ddns.',
@ -491,6 +510,8 @@ elif args['sub']:
add_subdomain(args['sub'][0][0])
elif args['version']:
show_current_info()
elif args['force']:
updateip(True)
elif args['ipserver']:
ip_server(args['ipserver'][0][0],args['ipserver'][0][1])
elif args['api']:
@ -500,9 +521,7 @@ elif args['remove']:
elif args['local']:
local_add_subdomain(args['local'][0][0],args['local'][0][1])
else:
# get_ip()
# get_api()
updateip()
updateip(None)