生活随笔
收集整理的這篇文章主要介紹了
python3实现阿里云DDNS域名动态解析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一. 前言
- 家里部署了一臺NAS服務器,在公司平時都是通過IP訪問的,現在想更改為用域名去訪問,但是家里的寬帶都是動態的公網IP,每次IP變了都需要手動解析一次域名,這樣就比較麻煩,那怎么辦了?這個時候我們就可以用到阿里云DDSN來實現自動進行域名解析, 通過阿里云的SDK來添加修改域名解析,檢查本機公網IP與解析的IP是否一致,若不同則自動修改解析,達到動態解析的目的。
二.準備工作
準備一個公網IP(如何檢查家里的IP是否是公網IP,我們可以通過查看路由器wan口IP和通過百度獲取IP,查看兩個IP是否一致,如一致者是公網IP,反之者不是)阿里云域名獲取阿里云的accessKeyId和accessSecret(可以在阿里云控制臺個人中心直接獲取。建議使用RAM角色來進行權限控制,這樣的話安全風險較小)python3環境
三.詳細步驟
1.安裝依賴包
pip3 install aliyun
-python
-sdk
-core
-v3
pip3 install aliyun
-python
-sdk
-domain
pip3 install aliyun
-python
-sdk
-alidns
pip3 install requests
pip3 install beautifulsoup4
pip3 install lxml
2.單獨寫一個獲取公網IP的腳本(以下演示腳本網站為:ip.tool.chinaz.com,各位可自行通過其他地址獲取IP信息)
import requests
from bs4
import BeautifulSoup
import re
def getip():'''通過ip.tool.chinaz.com地址獲取當前公網ip'''url
= "https://ip.tool.chinaz.com/"headers
= {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}res
= requests
.get
(url
, headers
=headers
)soup
= BeautifulSoup
(res
.text
, "lxml")label
= soup
.find
('div', attrs
={'class': 'WhwtdWrap bor-b1s col-gray03'})label_1
= label
.find
("span")regular
= re
.findall
(r'">(.+?)</span>', str(label_1
))print(f"當前IP地址為:{regular[0]}")return regular
[0]if __name__
== "__main__":getip
()
3.編寫阿里云ddns動態域名解析
import json
from urllib
.request
import urlopen
from aliyunsdkcore
.client
import AcsClient
from aliyunsdkalidns
.request
.v20150109
.DescribeSubDomainRecordsRequest
import DescribeSubDomainRecordsRequest
class Dnscontroller:access_key_id
= ""access_key_secret
= ""domain
= ""name_ipv4
= "@"record_type
= "A"region
= "cn-shenzhen"def __init__(self
):self
.client
= AcsClient
(self
.access_key_id
,self
.access_key_secret
,self
.region
)def add(self
, DomainName
, RR
, Type
, Value
):from aliyunsdkalidns
.request
.v20150109
.AddDomainRecordRequest
import AddDomainRecordRequestrequest
= AddDomainRecordRequest
()request
.set_accept_format
('json')request
.set_DomainName
(DomainName
)request
.set_RR
(RR
)request
.set_Type
(Type
)request
.set_Value
(Value
)response
= self
.client
.do_action_with_exception
(request
)def update(self
, RecordId
, RR
, Type
, Value
):from aliyunsdkalidns
.request
.v20150109
.UpdateDomainRecordRequest
import UpdateDomainRecordRequestrequest
= UpdateDomainRecordRequest
()request
.set_accept_format
('json')request
.set_RecordId
(RecordId
)request
.set_RR
(RR
)request
.set_Type
(Type
)request
.set_Value
(Value
)response
= self
.client
.do_action_with_exception
(request
)def Get_IPv4(self
):request
= DescribeSubDomainRecordsRequest
()request
.set_accept_format
('json')request
.set_DomainName
(self
.domain
)request
.set_SubDomain
(self
.name_ipv4
+ '.' + self
.domain
)response
= self
.client
.do_action_with_exception
(request
) domain_list
= json
.loads
(response
) ipv4
= json
.load
(urlopen
('http://jsonip.com'))['ip']print("獲取到IPv4地址:%s" % ipv4
)if domain_list
['TotalCount'] == 0:self
.add
(self
.domain
, self
.name_ipv4
, self
.record_type
, ipv4
)print("新建域名解析成功")elif domain_list
['TotalCount'] == 1:if domain_list
['DomainRecords']['Record'][0]['Value'].strip
() != ipv4
.strip
():self
.update
(domain_list
['DomainRecords']['Record'][0]['RecordId'], self
.name_ipv4
, self
.record_type
, ipv4
)print("修改域名解析成功")else:print("IPv4地址沒變")elif domain_list
['TotalCount'] > 1:from aliyunsdkalidns
.request
.v20150109
.DeleteSubDomainRecordsRequest
import DeleteSubDomainRecordsRequestrequest
= DeleteSubDomainRecordsRequest
()request
.set_accept_format
('json')request
.set_DomainName
(self
.domain
)request
.set_RR
(self
.name_ipv4
)response
= self
.client
.do_action_with_exception
(request
)self
.add
(self
.domain
, self
.name_ipv4
, self
.record_type
, ipv4
)print("修改域名解析成功")if __name__
== "__main__":Dnscontroller
().Get_IPv4
()
三.部署腳本到centos7系統
1.centos7 安裝python3,鏈接: link
2.把alyddns.py文件上傳到服務器“/dns”目錄下,并賦予權限
cd
/dns
chmod
+x alyddns
.py
3.centos7下安裝python3 阿里云依賴庫
sudo pip3 install aliyun
-python
-sdk
-core
-v3
==2.13.10
pip3 install aliyun
-python
-sdk
-alidns
pip3 install aliyun
-python
-sdk
-domain
四.腳本設置定時運行
- CentOS內置有強大的計劃任務工具Crontab,如果系統里沒有則先使用yum安裝
1.安裝Crontab
yum install crontabs
2.查看Crontab狀態
service crond status
ntsysv
3.添加定時任務
crontab
-e
i
*/10 * * * * /usr
/bin/python3
/dns
/alyddns
.py
ESC
:wq
service crond restart
4.查看任務列表
crontab
-l
5.Crontab命令在線驗證工具
鏈接: link
總結
以上是生活随笔為你收集整理的python3实现阿里云DDNS域名动态解析的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。