title: ddns刷新腳本
date: 2017-07-10 09:53:06
tags: raspberry,樹(shù)莓派,nodejs,ddns
ddns刷新腳本
繼發(fā)布樹(shù)莓派保持網(wǎng)絡(luò)連接shell腳本之后低葫,很快就使用了花生殼來(lái)添加ddns.但是當(dāng)時(shí)偷懶使用的是傻瓜式的頻繁刷新,最近閑來(lái)無(wú)事開(kāi)始修改腳本赏枚。水平有限沒(méi)有使用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:'賬號(hào):密碼',
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);
});
}
- 用dns.lookup()獲取域名對(duì)應(yīng)的ip
- 調(diào)用GET:http://ddns.oray.com/checkip獲取當(dāng)前的外網(wǎng)ip
- 比較兩個(gè)ip是否相同栏赴,如果不同钧忽,使用花生殼提供的接口GET:http://ddns.oray.com/ph/update 接口刷新ddnsIP