Skip to content

Instantly share code, notes, and snippets.

@tolgahanakgun
Last active May 2, 2020 10:40
Show Gist options
  • Save tolgahanakgun/8754fa0f733b471988ee948241f102ec to your computer and use it in GitHub Desktop.
Save tolgahanakgun/8754fa0f733b471988ee948241f102ec to your computer and use it in GitHub Desktop.
# create a folder with name .duckdns in the current user
# fill the domain and token fields in the code below
# then create a file with name duck.py and copy the lines starting with #!/usr/bin/python3
# chmod +x duck.py
# then create an entry in crontab with the line below
# */15 * * * * ~/.duckdns/duck.py >> ~/.duckdns/cron.log 2>&1
#!/usr/bin/python3
import time
import requests
from pathlib import Path
log_file = Path('~/.duckdns/duck.log').expanduser()
max_lines_of_log = 500
domain_name = ''
token = ''
payload = {'domains': domain_name, 'token': token, 'ip': ''}
response = requests.get('https://www.duckdns.org/update', params=payload)
with open(log_file, 'r+') as f:
lines = f.readlines()
if len(lines) >= max_lines_of_log:
f.seek(0, 0)
f.writelines(lines[1:])
if response.status_code == 200 and response.text == 'OK':
f.write(time.strftime('%Y-%m-%d %H:%M:%S') + ' INFO ' + str(response.status_code) + ' ' + response.text.replace('\r', '', 1000).replace('\n', ' ', 1000) + '\n')
else:
f.write(time.strftime('%Y-%m-%d %H:%M:%S') + ' ERROR ' + str(response.status_code) + ' ' + response.text.replace('\r', '', 1000).replace('\n', ' ', 1000) + '\n')
f.close()
@tolgahanakgun
Copy link
Author

tolgahanakgun commented May 2, 2020

I changed it to python from bash sed because it is soo compilacated to deal with response body when it includes special characters like < > carriage return and new line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment