├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── config.sample.json ├── do_authentication.py ├── do_http_get.py └── download.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .idea/** 3 | .idea/ 4 | *.iml 5 | 6 | config.json 7 | 8 | zonefiles/ 9 | zonefiles/** 10 | 11 | __* 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2018 Internet Corporation for Assigned Names and 2 | Numbers (ICANN). All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the ICANN nor the names of its contributors 15 | may be used to endorse or promote products derived from this 16 | software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY ICANN AND CONTRIBUTORS ``AS IS'' AND ANY 19 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 21 | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ICANN OR CONTRIBUTORS BE 22 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | This project uses the following third party software: 2 | 3 | --------------------------------------------------------------- 4 | 5 | Apache HttpComponents Client 6 | Copyright 1999-2018 The Apache Software Foundation 7 | 8 | This product includes software developed at 9 | The Apache Software Foundation (http://www.apache.org/). 10 | 11 | Licensed under the Apache License 2.0. 12 | 13 | --------------------------------------------------------------- 14 | 15 | Jackson JSON processor 16 | 17 | Jackson is a high-performance, Free/Open Source JSON processing library. 18 | It was originally written by Tatu Saloranta (tatu.saloranta@iki.fi), and has 19 | been in development since 2007. 20 | It is currently developed by a community of developers, as well as supported 21 | commercially by FasterXML.com. 22 | 23 | Licensed under the Apache License 2.0. 24 | 25 | --------------------------------------------------------------- 26 | 27 | TestNG 28 | 29 | This project includes software developed by Cedric Beust (http://www.testng.org). 30 | 31 | Licensed under the Apache License 2.0. 32 | 33 | --------------------------------------------------------------- 34 | 35 | Apache License 36 | Version 2.0, January 2004 37 | http://www.apache.org/licenses/ 38 | 39 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 40 | 41 | 1. Definitions. 42 | 43 | "License" shall mean the terms and conditions for use, reproduction, 44 | and distribution as defined by Sections 1 through 9 of this document. 45 | 46 | "Licensor" shall mean the copyright owner or entity authorized by 47 | the copyright owner that is granting the License. 48 | 49 | "Legal Entity" shall mean the union of the acting entity and all 50 | other entities that control, are controlled by, or are under common 51 | control with that entity. For the purposes of this definition, 52 | "control" means (i) the power, direct or indirect, to cause the 53 | direction or management of such entity, whether by contract or 54 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 55 | outstanding shares, or (iii) beneficial ownership of such entity. 56 | 57 | "You" (or "Your") shall mean an individual or Legal Entity 58 | exercising permissions granted by this License. 59 | 60 | "Source" form shall mean the preferred form for making modifications, 61 | including but not limited to software source code, documentation 62 | source, and configuration files. 63 | 64 | "Object" form shall mean any form resulting from mechanical 65 | transformation or translation of a Source form, including but 66 | not limited to compiled object code, generated documentation, 67 | and conversions to other media types. 68 | 69 | "Work" shall mean the work of authorship, whether in Source or 70 | Object form, made available under the License, as indicated by a 71 | copyright notice that is included in or attached to the work 72 | (an example is provided in the Appendix below). 73 | 74 | "Derivative Works" shall mean any work, whether in Source or Object 75 | form, that is based on (or derived from) the Work and for which the 76 | editorial revisions, annotations, elaborations, or other modifications 77 | represent, as a whole, an original work of authorship. For the purposes 78 | of this License, Derivative Works shall not include works that remain 79 | separable from, or merely link (or bind by name) to the interfaces of, 80 | the Work and Derivative Works thereof. 81 | 82 | "Contribution" shall mean any work of authorship, including 83 | the original version of the Work and any modifications or additions 84 | to that Work or Derivative Works thereof, that is intentionally 85 | submitted to Licensor for inclusion in the Work by the copyright owner 86 | or by an individual or Legal Entity authorized to submit on behalf of 87 | the copyright owner. For the purposes of this definition, "submitted" 88 | means any form of electronic, verbal, or written communication sent 89 | to the Licensor or its representatives, including but not limited to 90 | communication on electronic mailing lists, source code control systems, 91 | and issue tracking systems that are managed by, or on behalf of, the 92 | Licensor for the purpose of discussing and improving the Work, but 93 | excluding communication that is conspicuously marked or otherwise 94 | designated in writing by the copyright owner as "Not a Contribution." 95 | 96 | "Contributor" shall mean Licensor and any individual or Legal Entity 97 | on behalf of whom a Contribution has been received by Licensor and 98 | subsequently incorporated within the Work. 99 | 100 | 2. Grant of Copyright License. Subject to the terms and conditions of 101 | this License, each Contributor hereby grants to You a perpetual, 102 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 103 | copyright license to reproduce, prepare Derivative Works of, 104 | publicly display, publicly perform, sublicense, and distribute the 105 | Work and such Derivative Works in Source or Object form. 106 | 107 | 3. Grant of Patent License. Subject to the terms and conditions of 108 | this License, each Contributor hereby grants to You a perpetual, 109 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 110 | (except as stated in this section) patent license to make, have made, 111 | use, offer to sell, sell, import, and otherwise transfer the Work, 112 | where such license applies only to those patent claims licensable 113 | by such Contributor that are necessarily infringed by their 114 | Contribution(s) alone or by combination of their Contribution(s) 115 | with the Work to which such Contribution(s) was submitted. If You 116 | institute patent litigation against any entity (including a 117 | cross-claim or counterclaim in a lawsuit) alleging that the Work 118 | or a Contribution incorporated within the Work constitutes direct 119 | or contributory patent infringement, then any patent licenses 120 | granted to You under this License for that Work shall terminate 121 | as of the date such litigation is filed. 122 | 123 | 4. Redistribution. You may reproduce and distribute copies of the 124 | Work or Derivative Works thereof in any medium, with or without 125 | modifications, and in Source or Object form, provided that You 126 | meet the following conditions: 127 | 128 | (a) You must give any other recipients of the Work or 129 | Derivative Works a copy of this License; and 130 | 131 | (b) You must cause any modified files to carry prominent notices 132 | stating that You changed the files; and 133 | 134 | (c) You must retain, in the Source form of any Derivative Works 135 | that You distribute, all copyright, patent, trademark, and 136 | attribution notices from the Source form of the Work, 137 | excluding those notices that do not pertain to any part of 138 | the Derivative Works; and 139 | 140 | (d) If the Work includes a "NOTICE" text file as part of its 141 | distribution, then any Derivative Works that You distribute must 142 | include a readable copy of the attribution notices contained 143 | within such NOTICE file, excluding those notices that do not 144 | pertain to any part of the Derivative Works, in at least one 145 | of the following places: within a NOTICE text file distributed 146 | as part of the Derivative Works; within the Source form or 147 | documentation, if provided along with the Derivative Works; or, 148 | within a display generated by the Derivative Works, if and 149 | wherever such third-party notices normally appear. The contents 150 | of the NOTICE file are for informational purposes only and 151 | do not modify the License. You may add Your own attribution 152 | notices within Derivative Works that You distribute, alongside 153 | or as an addendum to the NOTICE text from the Work, provided 154 | that such additional attribution notices cannot be construed 155 | as modifying the License. 156 | 157 | You may add Your own copyright statement to Your modifications and 158 | may provide additional or different license terms and conditions 159 | for use, reproduction, or distribution of Your modifications, or 160 | for any such Derivative Works as a whole, provided Your use, 161 | reproduction, and distribution of the Work otherwise complies with 162 | the conditions stated in this License. 163 | 164 | 5. Submission of Contributions. Unless You explicitly state otherwise, 165 | any Contribution intentionally submitted for inclusion in the Work 166 | by You to the Licensor shall be under the terms and conditions of 167 | this License, without any additional terms or conditions. 168 | Notwithstanding the above, nothing herein shall supersede or modify 169 | the terms of any separate license agreement you may have executed 170 | with Licensor regarding such Contributions. 171 | 172 | 6. Trademarks. This License does not grant permission to use the trade 173 | names, trademarks, service marks, or product names of the Licensor, 174 | except as required for reasonable and customary use in describing the 175 | origin of the Work and reproducing the content of the NOTICE file. 176 | 177 | 7. Disclaimer of Warranty. Unless required by applicable law or 178 | agreed to in writing, Licensor provides the Work (and each 179 | Contributor provides its Contributions) on an "AS IS" BASIS, 180 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 181 | implied, including, without limitation, any warranties or conditions 182 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 183 | PARTICULAR PURPOSE. You are solely responsible for determining the 184 | appropriateness of using or redistributing the Work and assume any 185 | risks associated with Your exercise of permissions under this License. 186 | 187 | 8. Limitation of Liability. In no event and under no legal theory, 188 | whether in tort (including negligence), contract, or otherwise, 189 | unless required by applicable law (such as deliberate and grossly 190 | negligent acts) or agreed to in writing, shall any Contributor be 191 | liable to You for damages, including any direct, indirect, special, 192 | incidental, or consequential damages of any character arising as a 193 | result of this License or out of the use or inability to use the 194 | Work (including but not limited to damages for loss of goodwill, 195 | work stoppage, computer failure or malfunction, or any and all 196 | other commercial damages or losses), even if such Contributor 197 | has been advised of the possibility of such damages. 198 | 199 | 9. Accepting Warranty or Additional Liability. While redistributing 200 | the Work or Derivative Works thereof, You may choose to offer, 201 | and charge a fee for, acceptance of support, warranty, indemnity, 202 | or other liability obligations and/or rights consistent with this 203 | License. However, in accepting such obligations, You may act only 204 | on Your own behalf and on Your sole responsibility, not on behalf 205 | of any other Contributor, and only if You agree to indemnify, 206 | defend, and hold each Contributor harmless for any liability 207 | incurred by, or claims asserted against, such Contributor by reason 208 | of your accepting any such warranty or additional liability. 209 | 210 | END OF TERMS AND CONDITIONS 211 | 212 | APPENDIX: How to apply the Apache License to your work. 213 | 214 | To apply the Apache License to your work, attach the following 215 | boilerplate notice, with the fields enclosed by brackets "[]" 216 | replaced with your own identifying information. (Don't include 217 | the brackets!) The text should be enclosed in the appropriate 218 | comment syntax for the file format. We also recommend that a 219 | file or class name and description of purpose be included on the 220 | same "printed page" as the copyright notice for easier 221 | identification within third-party archives. 222 | 223 | Copyright [yyyy] [name of copyright owner] 224 | 225 | Licensed under the Apache License, Version 2.0 (the "License"); 226 | you may not use this file except in compliance with the License. 227 | You may obtain a copy of the License at 228 | 229 | http://www.apache.org/licenses/LICENSE-2.0 230 | 231 | Unless required by applicable law or agreed to in writing, software 232 | distributed under the License is distributed on an "AS IS" BASIS, 233 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 234 | See the License for the specific language governing permissions and 235 | limitations under the License. 236 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | CZDS API Client in Python 2 | =========== 3 | 4 | This repository provides a Python example of how to download zone files via CZDS (Centralized Zone Data Service) REST API. 5 | A detail API Specs can be found [here.](https://github.com/icann/czds-api-client-java/tree/master/docs) 6 | 7 | There is also an example provided in Java. It can be found in [this repo.](https://github.com/icann/czds-api-client-java) 8 | 9 | Installation 10 | ------------ 11 | 12 | This script requires Python 3. It has been tested with Python 3.13.2 13 | 14 | It requires the `requests` extension library. Please checkout here to see how to install it - https://github.com/requests/requests 15 | 16 | Run 17 | --------------------- 18 | 19 | 1. Make a copy of the `config.sample.json` file and name it `config.json` 20 | 2. Edit `config.json` and fill in your information. 21 | 2. Run `python download.py` 22 | 23 | All the zone files will be saved in `working-directory`/zonefiles, `working-directory` is specified in `config.json`, 24 | or default to current directory if not specified in `config.json` 25 | 26 | By default, it will download all the APPOVED zone files. If you only want a subset of the zone files, specify the 27 | `tlds: []` in the `config.json`. Note: missing `tlds` or empty `[]` means downloadd all the APPROVED zone files. 28 | 29 | Documentation 30 | ------------- 31 | 32 | * CZDS REST API Specs - https://github.com/icann/czds-api-client-java/blob/master/docs/ICANN_CZDS_api.pdf 33 | 34 | Contributing 35 | ------------ 36 | 37 | Contributions are welcome. 38 | 39 | Other 40 | ----- 41 | 42 | Reference Implementation in Java: https://github.com/icann/czds-api-client-java 43 | -------------------------------------------------------------------------------- /config.sample.json: -------------------------------------------------------------------------------- 1 | { 2 | "icann.account.username": "username@example.com", 3 | "icann.account.password": "Abcdef#12345678", 4 | "authentication.base.url": "https://account-api.icann.org", 5 | "czds.base.url": "https://czds-api.icann.org", 6 | "working.directory": "/where/zonefiles/will/be/saved", 7 | "_comment": "Optional tlds: to specify a subset of tlds to download. Missing or empty [] means downloading all APPROVED tlds.", 8 | "tlds": [] 9 | } 10 | -------------------------------------------------------------------------------- /do_authentication.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | import sys 4 | import datetime 5 | 6 | def authenticate(username, password, authen_base_url): 7 | authen_headers = {'Content-Type': 'application/json', 8 | 'Accept': 'application/json'} 9 | 10 | credential = {'username': username, 11 | 'password': password} 12 | 13 | authen_url = authen_base_url + '/api/authenticate' 14 | 15 | response = requests.post(authen_url, data=json.dumps(credential), headers=authen_headers) 16 | 17 | status_code = response.status_code 18 | 19 | # Return the access_token on status code 200. Otherwise, terminate the program. 20 | if status_code == 200: 21 | access_token = response.json()['accessToken'] 22 | print('{0}: Received access_token:'.format(datetime.datetime.now())) 23 | print(access_token) 24 | return access_token 25 | elif status_code == 404: 26 | sys.stderr.write("Invalid url " + authen_url) 27 | exit(1) 28 | elif status_code == 401: 29 | sys.stderr.write("Invalid username/password. Please reset your password via web") 30 | exit(1) 31 | elif status_code == 500: 32 | sys.stderr.write("Internal server error. Please try again later") 33 | exit(1) 34 | else: 35 | sys.stderr.write("Failed to authenticate user {0} with error code {1}".format(username, status_code)) 36 | exit(1) 37 | -------------------------------------------------------------------------------- /do_http_get.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | def do_get(url, access_token): 4 | 5 | bearer_headers = {'Content-Type': 'application/json', 6 | 'Accept': 'application/json', 7 | 'Authorization': 'Bearer {0}'.format(access_token)} 8 | 9 | response = requests.get(url, params=None, headers=bearer_headers, stream=True) 10 | 11 | return response 12 | -------------------------------------------------------------------------------- /download.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | import os 4 | import datetime 5 | from email.message import Message 6 | from do_authentication import authenticate 7 | from do_http_get import do_get 8 | 9 | ############################################################################################################## 10 | # First Step: Get the config data from config.json file 11 | ############################################################################################################## 12 | 13 | try: 14 | if 'CZDS_CONFIG' in os.environ: 15 | config_data = os.environ['CZDS_CONFIG'] 16 | config = json.loads(config_data) 17 | else: 18 | config_file = open("config.json", "r") 19 | config = json.load(config_file) 20 | config_file.close() 21 | except Exception as e: 22 | sys.stderr.write("Error loading config.json file: %s\n" % str(e)) 23 | exit(1) 24 | 25 | # The config.json file must contain the following data: 26 | username = config['icann.account.username'] 27 | password = config['icann.account.password'] 28 | authen_base_url = config['authentication.base.url'] 29 | czds_base_url = config['czds.base.url'] 30 | tlds = config.get('tlds', []) 31 | 32 | # This is optional. Default to current directory 33 | working_directory = config.get('working.directory', '.') # Default to current directory 34 | 35 | if not username: 36 | sys.stderr.write("'icann.account.username' parameter not found in the config.json file\n") 37 | exit(1) 38 | 39 | if not password: 40 | sys.stderr.write("'icann.account.password' parameter not found in the config.json file\n") 41 | exit(1) 42 | 43 | if not authen_base_url: 44 | sys.stderr.write("'authentication.base.url' parameter not found in the config.json file\n") 45 | exit(1) 46 | 47 | if not czds_base_url: 48 | sys.stderr.write("'czds.base.url' parameter not found in the config.json file\n") 49 | exit(1) 50 | 51 | 52 | ############################################################################################################## 53 | # Second Step: authenticate the user to get an access_token. 54 | # Note that the access_token is global for all the REST API calls afterwards 55 | ############################################################################################################## 56 | 57 | print("Authenticate user {0}".format(username)) 58 | access_token = authenticate(username, password, authen_base_url) 59 | 60 | 61 | 62 | ############################################################################################################## 63 | # Third Step: Get the download zone file links 64 | ############################################################################################################## 65 | 66 | # Function definition for listing the zone links 67 | def get_zone_links(czds_base_url): 68 | global access_token 69 | 70 | links_url = czds_base_url + "/czds/downloads/links" 71 | links_response = do_get(links_url, access_token) 72 | 73 | status_code = links_response.status_code 74 | 75 | if status_code == 200: 76 | zone_links = links_response.json() 77 | print("{0}: The number of zone files to be downloaded is {1}".format(datetime.datetime.now(),len(tlds) or len(zone_links))) 78 | return zone_links 79 | elif status_code == 401: 80 | print("The access_token has been expired. Re-authenticate user {0}".format(username)) 81 | access_token = authenticate(username, password, authen_base_url) 82 | get_zone_links(czds_base_url) 83 | else: 84 | sys.stderr.write("Failed to get zone links from {0} with error code {1}\n".format(links_url, status_code)) 85 | return None 86 | 87 | 88 | # Get the zone links 89 | zone_links = get_zone_links(czds_base_url) 90 | if not zone_links: 91 | exit(1) 92 | 93 | 94 | 95 | ############################################################################################################## 96 | # Fourth Step: download zone files 97 | ############################################################################################################## 98 | 99 | def _parse_header(header): 100 | m = Message() 101 | m['content-type'] = header 102 | return m 103 | 104 | # Function definition to download one zone file 105 | def download_one_zone(url, output_directory): 106 | print("{0}: Downloading zone file from {1}".format(str(datetime.datetime.now()), url)) 107 | 108 | global access_token 109 | download_zone_response = do_get(url, access_token) 110 | 111 | status_code = download_zone_response.status_code 112 | 113 | if status_code == 200: 114 | # Try to get the filename from the header 115 | option = _parse_header(download_zone_response.headers['content-disposition']) 116 | filename = option.get_param('filename') 117 | 118 | # If could get a filename from the header, then makeup one like [tld].txt.gz 119 | if not filename: 120 | filename = url.rsplit('/', 1)[-1].rsplit('.')[-2] + '.txt.gz' 121 | 122 | # This is where the zone file will be saved 123 | path = '{0}/{1}'.format(output_directory, filename) 124 | 125 | with open(path, 'wb') as f: 126 | for chunk in download_zone_response.iter_content(1024): 127 | f.write(chunk) 128 | 129 | print("{0}: Completed downloading zone to file {1}".format(str(datetime.datetime.now()), path)) 130 | 131 | elif status_code == 401: 132 | print("The access_token has been expired. Re-authenticate user {0}".format(username)) 133 | access_token = authenticate(username, password, authen_base_url) 134 | download_one_zone(url, output_directory) 135 | elif status_code == 404: 136 | print("No zone file found for {0}".format(url)) 137 | else: 138 | sys.stderr.write('Failed to download zone from {0} with code {1}\n'.format(url, status_code)) 139 | 140 | # Function definition for downloading all the zone files 141 | def download_zone_files(urls, working_directory): 142 | 143 | # The zone files will be saved in a sub-directory 144 | output_directory = working_directory + "/zonefiles" 145 | 146 | if not os.path.exists(output_directory): 147 | os.makedirs(output_directory) 148 | 149 | # Download the zone files one by one 150 | for link in urls: 151 | if len(tlds): 152 | for tld in tlds: 153 | if link.endswith('%s.zone' % tld): 154 | download_one_zone(link, output_directory) 155 | else: 156 | download_one_zone(link, output_directory) 157 | 158 | # Finally, download all zone files 159 | start_time = datetime.datetime.now() 160 | download_zone_files(zone_links, working_directory) 161 | end_time = datetime.datetime.now() 162 | 163 | print("{0}: DONE DONE. Completed downloading all zone files. Time spent: {1}".format(str(end_time), (end_time-start_time))) 164 | --------------------------------------------------------------------------------