CentOS通过DNSpod实现DDNS动态域名,在家也可以搭建主机服务器了

 

几篇参考文章:
1、http://www.anrip.com/post/872
2、http://fengwan.blog.51cto.com/508652/1404534/
源码地址:https://github.com/anrip/ArDNSPod

只是源码只能实现获取本地IP,若是有路由器,仅能获得内网地址。,要向获得外网地址:需要结合两篇文章。
两个文件,放到/usr/bin下面。
第一个文件,ddnspod.sh:

[php]
#!/bin/sh

#################################################
# AnripDdns v5.08
# Dynamic DNS using DNSPod API
# Original by anrip<mail@anrip.com>, http://www.anrip.com/ddnspod
# Edited by ProfFan
#################################################

# OS Detection
case $(uname) in
'Linux')
echo "Linux"
arIpAddress() {
local extip
extip='http://members.3322.org/dyndns/getip'
echo $extip
}
;;
'FreeBSD')
echo 'FreeBSD'
exit 100
;;
'WindowsNT')
echo "Windows"
exit 100
;;
'Darwin')
echo "Mac"
arIpAddress() {
ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}'
}
;;
'SunOS')
echo 'Solaris'
exit 100
;;
'AIX')
echo 'AIX'
exit 100
;;
*) ;;
esac

# Get script dir
# See: http://stackoverflow.com/a/29835459/4449544
rreadlink() ( # Execute the function in a *subshell* to localize variables and the effect of `cd`.

target=$1 fname= targetDir= CDPATH=

# Try to make the execution environment as predictable as possible:
# All commands below are invoked via `command`, so we must make sure that `command`
# itself is not redefined as an alias or shell function.
# (Note that command is too inconsistent across shells, so we don't use it.)
# `command` is a *builtin* in bash, dash, ksh, zsh, and some platforms do not even have
# an external utility version of it (e.g, Ubuntu).
# `command` bypasses aliases and shell functions and also finds builtins
# in bash, dash, and ksh. In zsh, option POSIX_BUILTINS must be turned on for that
# to happen.
{ \unalias command; \unset -f command; } >/dev/null 2>&1
[ -n "$ZSH_VERSION" ] && options[POSIX_BUILTINS]=on # make zsh find *builtins* with `command` too.

while :; do # Resolve potential symlinks until the ultimate target is found.
[ -L "$target" ] || [ -e "$target" ] || { command printf '%s\n' "ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[ "$fname" = '/' ] && fname='' # !! curiously, `basename /` returns '/'
if [ -L "$fname" ]; then
# Extract [next] target path, which may be defined
# *relative* to the symlink's own directory.
# Note: We parse `ls -l` output to find the symlink target
# which is the only POSIX-compliant, albeit somewhat fragile, way.
target=$(command ls -l "$fname")
target=${target#* -> }
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we have a normalized path.
if [ "$fname" = '.' ]; then
command printf '%s\n' "${targetDir%/}"
elif [ "$fname" = '..' ]; then
# Caveat: something like /var/.. will resolve to /private (assuming /var@ -> /private/var), i.e. the '..' is applied
# AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)

DIR=$(dirname -- "$(rreadlink "$0")")

# Global Variables:

# Token-based Authentication
arToken=""
# Account-based Authentication
arMail=""
arPass=""

# Load config

#. $DIR/dns.conf

# Get Domain IP
# arg: domain
arNslookup() {
#wget --quiet --output-document=- $inter$1
echo ""
}

# Get data
# arg: type data
arApiPost() {
local agent="AnripDdns/5.07(ligel@163.com)"
local inter="https://dnsapi.cn/${1:?'Info.Version'}"
if [ "x${arToken}" = "x" ]; then # undefine token
local param="login_email=${arMail}&login_password=${arPass}&format=json&${2}"
else
local param="login_token=${arToken}&format=json&${2}"
fi
wget --quiet --no-check-certificate --output-document=- --user-agent=$agent --post-data $param $inter
}

# Update
# arg: main domain sub domain
arDdnsUpdate() {
local domainID recordID recordRS recordCD myIP
# Get domain ID
domainID=$(arApiPost "Domain.Info" "domain=${1}")
domainID=$(echo $domainID | sed 's/.*{"id":"\([0-9]*\)".*/\1/')

# Get Record ID
recordID=$(arApiPost "Record.List" "domain_id=${domainID}&sub_domain=${2}")
recordID=$(echo $recordID | sed 's/.*\[{"id":"\([0-9]*\)".*/\1/')

# Update IP
myIP=$(arIpAddress)
recordRS=$(arApiPost "Record.Ddns" "domain_id=${domainID}&record_id=${recordID}&sub_domain=${2}&record_type=A&value=${myIP}&record_line=默认")
recordCD=$(echo $recordRS | sed 's/.*{"code":"\([0-9]*\)".*/\1/')

# Output IP
if [ "$recordCD" = "1" ]; then
echo $recordRS | sed 's/.*,"value":"\([0-9\.]*\)".*/\1/'
return 1
fi
# Echo error message
echo $recordRS | sed 's/.*,"message":"\([^"]*\)".*/\1/'
}

# DDNS Check
# Arg: Main Sub
arDdnsCheck() {
local postRS
local hostIP=$(arIpAddress)
local lastIP=$(arNslookup "${2}.${1}")
echo "hostIP: ${hostIP}"
echo "lastIP: ${lastIP}"
if [ "$lastIP" != "$hostIP" ]; then
postRS=$(arDdnsUpdate $1 $2)
echo "postRS: ${postRS}"
if [ $? -ne 1 ]; then
return 0
fi
fi
return 1
}

# DDNS
#echo ${#domains[@]}
#for index in ${!domains[@]}; do
# echo "${domains[index]} ${subdomains[index]}"
# arDdnsCheck "${domains[index]}" "${subdomains[index]}"
#done

. $DIR/dns.conf

[/php]

第二个文件,dns.conf:

[php]
# For security reasons, it is recommended that you use token-based auth instead
# arMail="test@gmail.com"
# arPass="123"

# Combine your token ID and token together as follows
arToken="12345,7676f344eaeaea9074c123451234512d"

# Place each domain you want to check as follows
# you can have multiple arDdnsCheck blocks
arDdnsCheck "test.org" "subdomain"
[/php]

增加执行权限

[php]chmod +x /root/ddnspod.sh[/php]

加入任务计划(5分钟执行一次)

[php]echo "*/5 * * * * root /root/ddnspod.sh" >> /etc/crontab[/php]

计划任务执行情况可以查看/var/log/cron
说明:
如果在执行后发现

[php]
[root@localhost ~]# ./ddnspod.sh
./ddns.sh: line 24: nslookup: command not found
hostIP: 114.234.77.222
lastIP:
postRS: 114.234.77.222[/php]

如果你使用的是CentOS则执行

[php]yum -y install bind-utils[/php]

或者是ubuntu的话

[php]sudo apt-get install dnsutils[/php]

 

 

 

 

CentOS通过DNSpod实现动态域名

rong341233关注0人评论6012人阅读2014-04-29 14:01:41

因为家里使用ADSL动态IP上网,有时在外面需要使用家里资源,原本使用的是TP-LINK自带的花生壳解析,用过之后发现很不稳定。因为自己注册了域名也已使用了DNSPOD解析。

1.新建脚本文件

<span style="color:#333333"><span style="color:#567482">vim ddns.sh</span></span>

文件内容如下:

<span style="color:#333333"><span style="color:#567482">#!/bin/sh
                                                                                                                                                                                                                                                                     

                                                                                                                                                                                                                                                                     
# 全局变量表
arPass=arMail=""
                                                                                                                                                                                                                                                                     
# 获得外网地址
arIpAdress() {
    local inter="http://members.3322.org/dyndns/getip"
    wget --quiet --no-check-certificate --output-document=- $inter
}
                                                                                                                                                                                                                                                                     
# 查询域名地址
# 参数: 待查询域名
arNslookup() {
    local dnsvr="114.114.114.114"
    nslookup ${1} $dnsvr | tr -d '\n[:blank:]' | awk -F':' '{print $6}'
}
                                                                                                                                                                                                                                                                     
# 读取接口数据
# 参数: 接口类型 待提交数据
arApiPost() {
    local agent="Ddns/3.08"
    local inter="https://dnsapi.cn/${1:?'Info.Version'}"
    local param="login_token=${arID},${arToken}&format=json&${2}"
    wget --quiet --no-check-certificate --output-document=- --user-agent=$agent --post-data $param $inter
}
                                                                                                                                                                                                                                                                     
# 更新记录信息
# 参数: 主域名 子域名
arDdnsUpdate() {
    local domainID recordID recordRS recordCD
    # 获得域名ID
    domainID=$(arApiPost "Domain.Info" "domain=${1}")
    domainID=$(echo $domainID | sed 's/.\+{"id":"\([0-9]\+\)".\+/\1/')
    # 获得记录ID
    recordID=$(arApiPost "Record.List" "domain_id=${domainID}&sub_domain=${2}")
    recordID=$(echo $recordID | sed 's/.\+\[{"id":"\([0-9]\+\)".\+/\1/')
    # 更新记录IP
    recordRS=$(arApiPost "Record.Ddns" "domain_id=${domainID}&record_id=${recordID}&sub_domain=${2}&record_line=默认")
    recordCD=$(echo $recordRS | sed 's/.\+{"code":"\([0-9]\+\)".\+/\1/')
    # 输出记录IP
    if [ "$recordCD" == "1" ]; then
        echo $recordRS | sed 's/.\+,"value":"\([0-9\.]\+\)".\+/\1/'
        return 1
    fi
    # 输出错误信息
    echo $recordRS | sed 's/.\+,"message":"\([^"]\+\)".\+/\1/'
}
# 动态检查更新
# 参数: 主域名 子域名
arDdnsCheck() {
    local postRS
    local hostIP=$(arIpAdress)
    local lastIP=$(arNslookup "${2}.${1}")
    echo "hostIP: ${hostIP}"
    echo "lastIP: ${lastIP}"
    if [ "$lastIP" != "$hostIP" ]; then
        postRS=$(arDdnsUpdate $1 $2)
        echo "postRS: ${postRS}"
        if [ $? -ne 1 ]; then
            return 0
        fi
    fi
    return 1
}
                                                                                                                                                                                                                                                                     
###################################################
                                                                                                                                                                                                                                                                     
# 设置用户参数
arID="89322"
arToken="3222w2e3213e123421421424234"
#填写账户的API token
 
                                                                                                                                                                                                                                                                     
# 检查更新域名
arDdnsCheck "anrip.com" "lab"</span></span>

ps:以上代码来自http://www.anrip.com/post/872

我们只需要将上面的

# 设置用户参数

arID="user@anrip.com"     //DNSPOD的API ID

arToken="anrip.net"                //DNSPOD的API Token

# 检查更新域名

arDdnsCheck"anrip.com"  "lab"     //需要更新的域名为anrip.com,主机为lab,就是lab.anrip.com

arDdnsCheck"anrip.net"  "lab"      //更新lab.anrip.net

修改成自己的信息即可

 

3.增加执行权限

<span style="color:#333333"><span style="color:#567482">chmod +x /root/ddns.sh</span></span>

 

4.加入任务计划(5分钟执行一次)

<span style="color:#333333"><span style="color:#567482">echo "*/5  * * * * root /root/ddns.sh" >> /etc/crontab</span></span>

 

计划任务执行情况可以查看/var/log/cron

说明:

如果在执行后发现

<span style="color:#333333"><span style="color:#567482">[root@localhost ~]# ./ddns.sh
./ddns.sh: line 24: nslookup: command not found
hostIP: 114.234.77.222
lastIP:
postRS: 114.234.77.222</span></span>

如果你使用的是CentOS则执行

<span style="color:#333333"><span style="color:#567482">yum -y install bind-utils</span></span>

或者是ubuntu的话

<span style="color:#333333"><span style="color:#567482">sudo apt-get install dnsutils</span></span>
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CentOS 系统上搭建 Web 服务器的步骤如下: 1. 安装 Apache HTTP 服务器:可以使用以下命令在 CentOS 系统上安装 Apache: ``` sudo yum install httpd ``` 2. 安装 MySQL 数据库:可以使用以下命令在 CentOS 系统上安装 MySQL: ``` sudo yum install mysql-server ``` 3. 安装 PHP:可以使用以下命令在 CentOS 系统上安装 PHP: ``` sudo yum install php php-mysql ``` 4. 配置 Apache:可以使用 Apache 的配置文件来配置服务器。在 CentOS 系统上,配置文件位于 /etc/httpd/conf/httpd.conf。可以编辑此文件来添加虚拟主机、配置目录和文件权限等。 5. 启动服务:在安装和配置 Apache、MySQL 和 PHP 后,可以使用以下命令启动 Apache 和 MySQL 服务: ``` sudo systemctl start httpd sudo systemctl start mysqld ``` 现在,Web 服务器已经搭建好了。如果您想从外部访问服务器,还需要进行以下步骤: 1. 配置防火墙:在服务器上打开防火墙端口,以便外部网络可以访问您的 Web 服务器。例如,在 CentOS 系统上,可以使用以下命令允许 HTTP 流量: ``` sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --reload ``` 2. 配置路由器:如果您使用的是家庭网络,可能需要在路由器上配置端口转发,以便从外部网络访问您的 Web 服务器。具体步骤因路由器型号而异,可以参考路由器的用户手册。 完成上述步骤后,您应该可以从外部网络访问您的 Web 服务器了。可以通过在 Web 浏览器中输入服务器的公共 IP 地址来测试访问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值