First, the application background is introduced : It is used to make the domain name correspond to the dynamic correctly IP. Then it introduces the functions that need to be used to complete this function API Interface , And the corresponding API Interface call framework . Finally, in order to use it more succinctly , The program logic is further optimized . Practice proves that truth is in practice !
Well known , General household broadband is that many lines share one exit IP Of . But for Telecom broadband , Due to telecommunications IP More , So by installing a home camera excuse To apply for the public network IP. But to prevent users from using ip Build indescribable services at home , The public network provided by telecom IP It's usually dynamic IP, And it's sealed 80,443,8080 port . According to the author's observation , Broadband outlet IP Change every three days , namely 72 Change every hour . meanwhile , If the light cat in the house restarts within three days , Or in case of power failure and power failure ,IP The address will also change . Therefore, when using home broadband to provide Internet services , The first thing that needs to be solved is the changing IP The question of address .
At present, there are many dynamic domain name resolution services in the market (DDNS), That is, according to your current IP Address , Real time modification of the corresponding domain name on the public name server A Record , So that users can correctly reach your server address when accessing your domain name . Some of the more famous ones are :
It can be seen from the market research ,DDNS The relevant market is quite mature , Users also tend to be saturated , Therefore, this article is suitable for those who do not want to use the services of the above platform providers but prefer DIY fiddle Classmate . Through the clouds + The search results of the community can see ( As shown in the figure below ), At present, the community has no tutorial to teach you how to realize dynamic domain name resolution , So the main purpose of this article is to use python Realize free dynamic domain name resolution capability , Because the cloud of Tencent cloud API Functions improve development efficiency , So the cloud API This development artifact is worthy of further promotion .
First, you need to have a domain name resolved on Tencent cloud ( I really only have one ), As shown in the figure below :
Then click on the avatar in the upper right corner , Get into API secret key page , As shown in the figure below :
Tencent's cloud API Key interface APPID Corresponding ID and Key that will do , As shown in the figure below :
Keep your key , For later use ! This article appears in all SecretID The place of , Unified use ID Instead of ; The key appears in all SecretKey The place of , Unified use Key Instead of .
All experimental methods and results are based on the following assumptions :
First log in to Tencent cloud , Look up DNSPod Related documents of , Document address :https://cloud.tencent.com/document/product/1427/56194. It lists a series of related interface lists , We may need to use the following related API Interface , As shown in the following table :
API name
describe
DescribeRecordList
Get the resolution record of domain name
CreateRecord
Add records
ModifyRecord
Modify the record
ModifyDynamicDNS
Updates DNS Record
My understanding is that , The third interface is a combination of the first interface and the second interface : Get the existing parsing list first , Then find out whether there is a resolution record for the corresponding subdomain name , If it exists, modify the record value of the subdomain name , If it does not exist, add a new record . The following is about the combination of Tencent cloud API Explorer Implement the third interface , cloud API Explorer The address for :ModifyDynamicDNS. The operation interface is shown in the figure below :
Observe the required parameters , Found a parameter RecordId For the record to be modified ID, This parameter passes through DescribeRecordList Interface acquisition , If I need to modify an existing record directly , Record the records that need to be modified ID, After the call ModifyDynamicDNS Interface ; If you need to create a new record , And dynamically update the recorded value , You can use it first CreateRecord Interface , Record create a good record ID, Directly in ModifyDynamicDNS Used in the interface .
This example is to dynamically modify existing records , So combine DescribeRecordList Interface and ModifyDynamicDNS Interface to realize dynamic domain name resolution . First of all, from the DescribeRecordList The interface document page enters API Explorer Interface , Configure relevant parameters , As shown in the figure below :
After the parameters are configured , The corresponding request code will be generated on the right , This example tutorial uses Python SDK, So copy python Code to local , Create a new one DDNS.py file , As shown in the figure below :
One of them involves the Tencent cloud public request module tencentcloud.common, The module can be accessed through pip Command to install , Document address :python SDK, The installation command is as follows :
$ pip install --upgrade tencentcloud-sdk-python
Let's take the figure above, No 9 Yes "SecretId", "SecretKey" Change to the one we saved before ID and Key, Run directly to get a lot of JSON, Here we show the normal return Response Some properties of the object :
"Response": {
"RequestId": "a3bee0a2-bac6-43db-b76d-a4ce11cec0c7",
"RecordCountInfo": {
"SubdomainCount": 23,
"TotalCount": 23,
"ListCount": 23
},
"RecordList": [
{
"Value": "59.52.241.247",
"Status": "ENABLE",
"UpdatedOn": "2021-08-13 20:03:43",
"Name": "homesource",
"Line": " Default ",
"LineId": "0",
"Type": "A",
"Weight": null,
"MonitorStatus": "",
"Remark": "",
"RecordId": 760223447,
"TTL": 600,
"MX": 0
}
]
} The name is homesource Our records are those we need to update , The corresponding result is RecordId by 760223447. We save this value , Waiting for a backup .
And do the same , What will be obtained RecordId Substitute into ModifyDynamicDNS Interface , Of this interface API Explorer The address is :ModifyDynamicDNS As shown in the figure below :
Found by testing SubDomain Parameter should be Will options , If you don't add this parameter , This interface will be modified by default @ Parameter values recorded by the host . Copy the generated code locally , Remove the duplicate modules and import the rest as shown in the following figure :
Put your ID and Key Replace... In the code "SecretId", "SecretKey", Run the code directly , The result of the request is as follows :
{
"RecordId": 760223447,
"RequestId": "2542afb0-bc7c-4c2e-b864-ca1d73795cdf"
} go back to DNSPod Console view API Operating results , As shown in the figure below :
You can see that the value of this record has been successfully modified to 127.0.0.1, In practical application, the IP Change the address to other IP address , be based on API Explorer Of DDNS The request framework has been set up , The following is a further optimization based on the progressive application mode .
Because the current content has only a simple framework , To make it easier to use, you need to add more content .
In the above , We use the naked eye to find the resolution records that need to be modified in a large number of resolution records RecordId. But this approach is inefficient , The implementation here is based on the request result , Automatically return the specified subdomain name RecordId.
Implementation logic :
RecordId Host record value of Name The same record as the specified host record , return RecordIdThe modified code for obtaining the record list of the domain name is changed as follows :
def ReturnRecordId(Domain, SubDomain):
try:
cred = credential.Credential(SecretId, SecretKey)
httpProfile = HttpProfile()
httpProfile.endpoint = "dnspod.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = dnspod_client.DnspodClient(cred, "", clientProfile)
req = models.DescribeRecordListRequest()
params = {
"Domain": Domain
}
req.from_json_string(json.dumps(params))
resp = client.DescribeRecordList(req)
for record in resp.RecordList:
if record.Name == SubDomain:
return record.RecordId
print(" Corresponding record value not found , Please create the corresponding host record first !")
return -2
except TencentCloudSDKException as err:
print(" Failed to get the record list of domain name , Please try again !")
return -1 Packaged ModifyDynamicDNS The function is shown below :
def ModifyDynamicDNS(RecordId, Domain ,SubDomain, Ip):
try:
cred = credential.Credential(SecretId, SecretKey)
httpProfile = HttpProfile()
httpProfile.endpoint = "dnspod.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = dnspod_client.DnspodClient(cred, "", clientProfile)
req = models.ModifyDynamicDNSRequest()
params = {
"Domain": Domain,
"SubDomain": SubDomain,
"RecordId": RecordId,
"RecordLine": " Default ",
"Value": Ip
}
req.from_json_string(json.dumps(params))
resp = client.ModifyDynamicDNS(req)
if str(RecordId) in resp.to_json_string():
print(" The update is successful !")
return 1
except TencentCloudSDKException as err:
return 0 Implementation dynamics DNS analysis , First, get the current local public network IP, Then change IP Submit to the appropriate API in . At present, there are many free public local IP Query interface , Here we choose :https://ip.tool.lu/, This site returns faster results , But the result is not standard JSON Or other standard data formats , As shown below :
At present IP: 59.52.217.194 Place of ownership : China jiangxi nanchang
So first we process the data , extract IP Address .
then , In obtaining IP After address and before IP Address comparison , Judge IP Is there a change , If there is a change, pass the change through API Submit .IP Check to run at regular intervals , Guarantee IP Detect all directions without dead angle ! Here we use regular expressions and request Module to complete IP Extraction method , The code is as follows :
import requests
import re
def GetCurrentIP():
resp = requests.get('https://ip.tool.lu/').content
resp = resp.decode('utf8')
IPPattern = '\d+.\d+.\d+.\d+'
matchObj = re.search(IPPattern, resp)
return matchObj.group()
ip = GetCurrentIP()Check the current... At regular intervals IP Whether with the previous IP identical , The time interval specified here is 10 minute , The implementation code is shown in the following figure :
import time
interval = 600 # Every time 10 Check every minute IP
OldIP = ""
while True:
CurrentIP = GetCurrentIP()
if OldIP != CurrentIP:
res = ModifyDynamicDNS(RecordId=RecordId, Domain=Domain, SubDomain=SubDomain, Ip = CurrentIP)
if res:
print(f'IP Successful update ! primary IP:{OldIP}, new IP:{CurrentIP}')
OldIP = CurrentIP
else:
print(' Dynamic domain name resolution API Something is wrong. , Retrying !')
continue
time.sleep(interval) From this logic, we can see , When the program first runs , primary IP It's not shown , But when IP After modification , primary IP It will display normally . Sort out the above IP Update logic , Update it to DDNS.py In file , The main function code is as follows :
if __name__ == "__main__":
SecretId = ""
SecretKey = ""
Domain = "eatrice.cn" # The main domain name
SubDomain = "homesource" # Specify the subdomain name to modify
interval = 600 # Every time 10 Check every minute IP
RecordId = ReturnRecordId(Domain=Domain, SubDomain=SubDomain)
if RecordId == -1:
print("RecordList There is a problem with the request !")
exit()
if RecordId == -2:
print(" The subdomain you want is not found , Please create a new !")
OldIP = ""
while True:
CurrentIP = GetCurrentIP()
if OldIP != CurrentIP:
res = ModifyDynamicDNS(RecordId=RecordId, Domain=Domain, SubDomain=SubDomain, Ip = CurrentIP)
if res:
print(f'IP Successful update ! primary IP:{OldIP}, new IP:{CurrentIP}')
OldIP = CurrentIP
else:
print(' Dynamic domain name resolution API Something is wrong. , Retrying !')
continue
time.sleep(interval) thus , be based on API Explorer The tutorial of local implementation of dynamic domain name resolution has been completed . The complete source code has been open source to GitHub, Address :QiQiWan/PythonDDNS
household IP It's dynamic and really annoying , But it can be combined with DNSPod Realize the curve to save the country , Practice has proved , There are more ways than difficulties ! Another thing worth mentioning API Explorer It's an artifact. , Mom doesn't have to worry about doing it anymore API There was a problem requesting , Saved a lot of things , That's good !