ddns刷新腳本


title: ddns刷新腳本
date: 2017-07-10 09:53:06
tags: raspberry,樹莓派,nodejs,ddns


ddns刷新腳本

繼發(fā)布樹莓派保持網絡連接shell腳本之后,很快就使用了花生殼來添加ddns.但是當時偷懶使用的是傻瓜式的頻繁刷新,最近閑來無事開始修改腳本。水平有限沒有使用shell腳本,使用的是node.js的腳本

node.js腳本

var http = require('http');
var dns = require('dns');
var fs = require('fs');

var currentIp = "";

dns.lookup('域名', function(err, address, family){
    if(err) throw err;
    currentIp = address;
    checkIP();
});

function checkIP(){
    var options = {
        hostname:'ddns.oray.com',
        port:80,
        path:'/checkip',
        method:'GET',
    }
    var req = http.request(options, function (res){
        res.setEncoding('utf8');
        res.on('data',function(chunk){
            var location = chunk.indexOf('Current IP Address: ');
            if (location>=0) {
                var lastLocation = chunk.indexOf('</body></html>');
                var subString = chunk.substring(location+20,lastLocation);
                fileLogl(Date()+subString);
                if(currentIp === subString){
                }else{
                    fileLogl('currentIp:'+currentIp+'selfIp:'+subString);
                    updateMyIp(subString);
                }
            };
        });
    });
    req.on('error',function(e){
        fileLogl(e);
    });
    req.end();
}

function updateMyIp(ip){
    fileLogl('更新IP'+ip);
    if(ip.length>0){
        var options = {
            auth:'賬號:密碼',
            hostname:'ddns.oray.com',
            port:80,
            path:'/ph/update',
            method:'GET',
            params:{
                hostname:'域名',
                myip:ip
            },
            headers:{
                'user-agent':'Oray'
            }
        }
        var req = http.request(options, function (res){
            fileLogl(res.statusCode);
            res.setEncoding('utf8');
            res.on('data',function(chunk){
                fileLogl(chunk);
            });
        });
        req.on('error',function(e){
            fileLogl(e);
        });
        req.end();
    }
}

function fileLogl(lstring){
    fs.appendFile('日志目錄/ddns.log', lstring+"\n", function (err) {
        console.log(err);
    });
}
  1. 用dns.lookup()獲取域名對應的ip
  2. 調用GET:http://ddns.oray.com/checkip獲取當前的外網ip
  3. 比較兩個ip是否相同,如果不同,使用花生殼提供的接口GET:http://ddns.oray.com/ph/update 接口刷新ddnsIP

定時運行

參考樹莓派保持網絡連接shell腳本

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容