Hero Illustration

usacloud-ddns

WordPress へようこそ。こちらは最初の投稿です。編集または削除し、コンテンツ作成を始めてください。

usacloud-ddns.py
#
#   Replace IP address in JSON file
#     for usacloud dynamic dns
#

import os
import sys
import urllib.request
import json

def getIPv4():
    try:
        with urllib.request.urlopen('http://v4.ident.me') as response:
            return response.read().decode()
    except urllib.error.URLError as e:
        print(e.reason)

temp1 = 'temp1.json'
temp2 = 'temp2.json'

# Command Argument
args = sys.argv
if len(args) < 2:
    print('Usage: python3 usacloud-ddns.py HOST [HOST2] ...')
    exit()

# Get IP Address
IPv4 = getIPv4()

# Read JSON file
with open(temp1) as jf:
    json_records = json.load(jf)

# Replace IP Address
changed = False
for i in range(1, len(args)):
    host = args[i]
    for rec in json_records:
        if rec['Name'] == host and rec['Type'] == 'A' and rec['RData'] != IPv4:
            changed = True
            print(host + "\t" + rec['Type'] + "\t" + rec['RData'] + ' -> ' + IPv4)
            rec['RData'] = IPv4

if changed:
    # Convert JSON to string
    js = json.dumps(json_records)
    js = js.replace(" ","")
    jz = '{"Records":' + js + '}'

    # for Windows
    if os.name == "nt":
        jz = '{\\"Records\\":' + js.replace('"', '\\"') + '}'

    # Write JSON file
    with open(temp2, "w") as jf:
        jf.write(jz)
        jf.close()
usacloud-ddns.sh
#!/bin/sh
export ID=
export HOST1=
export HOST2=
export TEMP1=temp1.json
export TEMP2=temp2.json
rm $TEMP2 2> /dev/null
usacloud dns read $ID --query '.[0].Records' > $TEMP1
python usacloud-ddns.py $HOST1 $HOST2
if [ -f ./$TEMP2 ]; then
  export JSON=`cat $TEMP2`
  usacloud dns update $ID --assumeyes --parameters "$JSON"
fi
usacloud-ddns.bat
@ECHO OFF
SET ID=
SET HOST1=
SET HOST2=
SET TEMP1=temp1.json
SET TEMP2=temp2.json
del /f %TEMP2% >NUL 2>&1
usacloud dns read %ID% --query ".[0].Records" > %TEMP1%
python usacloud-ddns.py %HOST1% %HOST2%
if EXIST %TEMP2% (
  GOTO USACLOUD
) ELSE (
  GOTO END
)
:USACLOUD
SET /p JSON=<%TEMP2%
usacloud dns update %ID% --assumeyes --parameters "%JSON%"
:END