-
Notifications
You must be signed in to change notification settings - Fork 43
Adding czds.py script #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jpleger
wants to merge
2
commits into
icann:master
Choose a base branch
from
jpleger:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
#!/usr/bin/env python3 | ||
import requests | ||
import json | ||
import os | ||
import argparse | ||
|
||
|
||
class AuthenticationError(Exception): | ||
pass | ||
|
||
|
||
class CZDSClient(object): | ||
czds_api_base = 'https://czds-api.icann.org' | ||
auth_api = 'https://account-api.icann.org/api/authenticate' | ||
request_headers = { | ||
'Content-Type': 'application/json', | ||
'Accept': 'application/json' | ||
} | ||
_token = None | ||
|
||
def __init__(self, username, password): | ||
self.username = username | ||
self.password = password | ||
|
||
def authenticate(self): | ||
""" | ||
Authenticate against the icann account api. | ||
|
||
:return: authorizaiton token | ||
""" | ||
creds = { | ||
'username': self.username, | ||
'password': self.password, | ||
} | ||
response = requests.post(self.auth_api, data=json.dumps(creds), headers=self.request_headers) | ||
if response.status_code == 401: | ||
raise AuthenticationError('Invalid Credentials') | ||
if response.status_code != 200: | ||
raise Exception('Invalid response code returned by server: {}'.format(response.status_code)) | ||
response_json = response.json() | ||
if 'accessToken' not in response_json: | ||
raise Exception('Access token not in json response: {}'.format(repr(response_json))) | ||
return response_json['accessToken'] | ||
|
||
@property | ||
def auth_headers(self): | ||
""" | ||
Return authenticated headers (lazy authentication when required) | ||
|
||
:return: headers dict | ||
""" | ||
if not self._token: | ||
self._token = self.authenticate() | ||
headers = {'Authorization': 'Bearer {}'.format(self._token)} | ||
headers.update(self.request_headers) | ||
return headers | ||
|
||
def download_zonefiles(self, dest_dir): | ||
""" | ||
Download Zonefiles | ||
:param dest_dir: directory to save zonefiles to | ||
:return: | ||
""" | ||
dest_dir = os.path.abspath(dest_dir) | ||
if not os.path.isdir: | ||
raise OSError('Invalid file path') | ||
links_url = self.czds_api_base + '/czds/downloads/links' | ||
zonefile_links = requests.get(links_url, headers=self.auth_headers).json() | ||
downloads = [] | ||
for z in zonefile_links: | ||
# Create a filename based off the zonefile name (zonename.zone.gz) | ||
filename = z.split('/')[-1] + '.gz' | ||
with open(os.path.join(dest_dir, filename), 'wb') as fh: | ||
response = requests.get(z, headers=self.auth_headers, stream=True) | ||
response_len = 0 | ||
for chunk in response.iter_content(chunk_size=1024): | ||
response_len += len(chunk) | ||
fh.write(chunk) | ||
downloads.append((filename, response_len)) | ||
return downloads | ||
|
||
def main(): | ||
parser = argparse.ArgumentParser() | ||
parser.add_argument('--username', '-u', dest='username', default=os.environ.get('ICANN_USER', None), | ||
help='ICANN Username') | ||
parser.add_argument('--password', '-p', dest='password', default=os.environ.get('ICANN_PASS', None), | ||
help='ICANN Password') | ||
parser.add_argument('--dest', '-d', dest='dest_dir', default=os.environ.get('DEST_DIR', '.'), | ||
help='Destination directory') | ||
args = parser.parse_args() | ||
if not args.username: | ||
print('No credentials defined!') | ||
parser.print_help() | ||
return | ||
try: | ||
print('Starting Zonefile Downloads') | ||
czds_client = CZDSClient(args.username, args.password) | ||
results = czds_client.download_zonefiles(args.dest_dir) | ||
print('Downloaded {} files'.format(len(results))) | ||
except AuthenticationError: | ||
print('Invalid Credentials, check user/password') | ||
parser.print_help() | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.