ddns刷新脚本


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


ddns刷新脚本

继发布树莓派保持网络连接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('');
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脚本

你可能感兴趣的:(ddns刷新脚本)