Screaming Loud

日々是精進

もうそろそろ規約変更になってしまうが・・・。

そういえば、昔書いてずっと使ってたDynamicDNS自動更新スクリプトがあったので、晒す。

#coding:utf-8
import subprocess
import re
import time
from optparse import OptionParser

CRT_IPF = '/usr/ddns/CRT_IP.dat'
NEW_IPF = '/usr/ddns/NEW_IP.dat'
LOG = '/var/log/ddns.log'
DOM = 'hoge' #ドメイン名
PASS = 'hoge' #パスワード

def IP_from_File(filename):
    '''get IP from a recorded file'''
    with open(filename,'r') as f:
        recom = 'REMOTE_ADDR:'
        for line in f:
            if re.search(recom,line):
                line = re.sub(recom,'',line)
                return line.rstrip()

def get_present_IP(output):
    '''get IP of this network'''
    subprocess.call("wget -q -O "+output+" http://info.ddo.jp/remote_addr.php",shell=True)

def write_IP(inputIP,outputFile):
    '''write to change IP'''
    stp = open(outputFile,'w')
    stp.write('REMOTE_ADDR:'+inputIP)
    stp.close()

def write_log(LOG,current_IP,new_IP):
    with  open(LOG,'a') as f:
        localtime = str(time.asctime())
        f.write(localtime+' DDNS IP Address Updated. '+str(current_IP)+' to '+new_IP+'\n')

if __name__ =='__main__':
    usage = 'usage: %prog [options]'
    parser = OptionParser(usage)
    parser.add_option('--update',dest='opt',action='append_const',default = [],const='ipupd',
                      help="force to update IP")
    (options,args) = parser.parse_args()

    current_IP = IP_from_File(CRT_IPF)
    get_present_IP(NEW_IPF)
    new_IP = IP_from_File(NEW_IPF)
    cmd = "wget -q -O - 'http://free.ddo.jp/dnsupdate.php?dn="+DOM+"&pw="+PASS+"'"
    print new_IP
    if (new_IP!='') and (current_IP!=new_IP):
        write_IP(new_IP,CRT_IPF)
        print "IP Address update: "+str(current_IP)+" to "+new_IP
        subprocess.call(cmd,shell=True)
        write_log(LOG,current_IP,new_IP)
    else:
        if 'ipupd' in options.opt:
            print "IP Address force to update: "+str(current_IP)+" to "+new_IP
            subprocess.call(cmd,shell=True)
            write_log(LOG,current_IP,new_IP)
        else:
            print 'No change IP :',current_IP