/
dyncli
executable file
·314 lines (262 loc) · 9.11 KB
/
dyncli
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/env python
import json
import argparse
import requests
from os import environ
from sys import exit
parser = argparse.ArgumentParser()
parser.add_argument('-e','--endpoint',dest='endpoint',default='https://api2.dynect.net/REST/',
help='The endpoint to make API requests.')
parser.add_argument('-c','--create',dest='create',
help='Create a new record. Defaults to A record unless --cname is set.')
parser.add_argument('--cname',dest='cname',action='store_true',
help='Create a cname record instead of an A record.')
parser.add_argument('-v','--value',dest='value',
help='The value to set the DNS record to. Eg 10.0.0.101.')
parser.add_argument('-t','--ttl',dest='ttl',type=int,default=300,
help='TTL of record in seconds.')
parser.add_argument('-d','--delete',dest='delete',
help='Delete an existing record')
parser.add_argument('-u','--update',dest='update_record',
help='Perform a DNS update on an existing record.')
parser.add_argument('-U','--user',dest='user',
help='The username to connect to the dyn api. Can also be set as DYN_USER in environment.')
parser.add_argument('-P','--password',dest='password',
help='The password to use with the dyn api. Can also be set as DYN_PW in environment.')
parser.add_argument('-A','--account',dest='account',
help='The account name used to make API requests. Can be set as DYN_ACCOUNT in environment.')
parser.add_argument('-Z','--zone',dest='zone',
help='The zone to take action on. Eg example.com. Can be set as DYN_ZONE in environment.')
parser.add_argument('-l','--list',dest='list',action='store_true',
help='List all dns records as a csv file.')
parser.add_argument('--verbose',dest='verbose',action='store_true',
help='Print out api responses.')
args = parser.parse_args()
config = {}
config['endpoint'] = args.endpoint
config['zone'] = args.zone
config['create'] = args.create
config['cname'] = args.cname
config['value'] = args.value
config['ttl'] = args.ttl
config['delete'] = args.delete
config['update_record'] = args.update_record
config['user'] = args.user
config['password'] = args.password
config['account'] = args.account
config['list'] = args.list
config['verbose'] = args.verbose
def error(msg,exit_code=1):
'''
Helper function for printing errors and exiting. Default exit code is 1.
'''
print("Error: %s" % msg)
exit(exit_code)
def verify_credentials():
'''
In order to make requests to the DYN api we need 4 pieces of auth info:
1. -U/--user or env['DYN_USER']
2. -P/--PASSWORD or env['DYN_PW']
3. -A/--account or env['DYN_ACCOUNT']
4. -Z/--zone or env['DYN_ZONE']
Check for the existence of these either as command line arguments or
environment variables. Command line arguments take precedence over ENV if
both are present.
'''
def test_env(local_var,env_var):
if not config[local_var]:
try:
config[local_var] = environ[env_var]
except KeyError:
error("%s not set on cmdline and %s not present in local environment"
% (local_var,env_var))
test_env('user','DYN_USER')
test_env('password','DYN_PW')
test_env('account','DYN_ACCOUNT')
test_env('zone','DYN_ZONE')
def call_dyn(suffix,method='get',data=None,detailed=False):
'''
Call the dyn api. Returns json object
'''
response = None
if data:
data = json.dumps(data)
url = config['endpoint'] + suffix
if detailed:
url = url + '?detail=y'
if config['verbose']:
print('Connecting to: ' + url)
header = {
'content-type': 'application/json',
'Accept': 'application/json'
}
if config.get('token'):
header['Auth-Token'] = config['token']
try:
response = getattr(requests, method)(url,headers=header,data=data)
except Exception, e:
error(e)
resp = json.loads(response.text)
if config['verbose']:
print json.dumps(resp,indent=2)
if resp['status'] != 'success':
error(resp['msgs'][0]['INFO'])
return resp
def get_token(credentials):
'''
Authenticates with Dyn. Returns a session token string if successful.
Requires a dict with the following:
dict['account']
dict['user']
dict['password]'
'''
suffix = 'Session/'
data = {
'customer_name': credentials['account'],
'user_name': credentials['user'],
'password': credentials['password']
}
# Squelch this message if we're printing a CSV
if not config['list']:
print('Initializing session...')
resp = call_dyn(suffix,method='post',data=data)
return resp['data']['token']
def list_records():
'''
Print all the records associated with a zone in a CSV format. Useful for
backing up a zone.
'''
suffix = 'AllRecord/%s/' % config['zone']
data = call_dyn(suffix,detailed=True)
records = []
# Print the initial CSV header
record_format = ['zone','ttl','fqdn','record_type','data']
records.append(','.join(record_format))
# Iterate over all of the DNS types
for dns_types in data['data'].values():
for dns_entry in dns_types:
# Dyn returns data in a strange format. Here we first try and grab the
# record data based on the record_type. If that fails we'll dump the data
# from dyn but transcribe the commas to pipes so it doesn't affect our
# formatting
address_data = None
if dns_entry['record_type'] == 'A':
address_data = dns_entry['rdata']['address']
elif dns_entry['record_type'] == 'CNAME':
address_data = dns_entry['rdata']['cname']
elif dns_entry['record_type'] == 'NS':
address_data = dns_entry['rdata']['nsdname']
elif dns_entry['record_type'] == 'TXT':
address_data = dns_entry['rdata']['txtdata']
else:
# Something funky
strange_format = []
for key, value in dns_entry['rdata'].iteritems():
formatted_entry = key + ':' + str(value)
strange_format.append(formatted_entry)
address_data = '|'.join(strange_format)
record = ','.join([
dns_entry['zone'],
str(dns_entry['ttl']),
dns_entry['fqdn'],
dns_entry['record_type'],
str(address_data),
])
records.append(record)
return records
def publish(zone):
'''
Publish changes we've made to dyn. No going back from here.
'''
data = {
'publish': 1
}
print zone
suffix = 'Zone/%s/' % zone
print('Attempting to publish zone...')
call_dyn(suffix,method='put',data=data)
def create_record(address):
'''
Create a record. First argument is a dict with dict['address'],
dict['value'], and optionally dict['ttl'].
'''
payload = {
'rdata': {},
'ttl': address['ttl']
}
if address['value'] == 'None':
error('Missing parameter -v/--value.')
if address['cname']:
payload['rdata']['cname'] = address['value']
suffix = "CNAMERecord/%s/%s/" % (address['zone'], address['create'])
else:
payload['rdata']['address'] = address['value']
suffix = "ARecord/%s/%s/" % (address['zone'], address['create'])
print('Attempting to create record...')
call_dyn(suffix,method='post',data=payload)
publish(config['zone'])
def update_record(address):
'''
Update an existing record. Accepts dict with 'update_record' and either
'value' or 'ttl' or both.
'''
suffix = "ARecord/%s/%s/" % (address['zone'], address['update_record'])
payload = {
'rdata': {}
}
if address.get('value'):
payload['rdata'] = {
'address': address['value']
}
if address.get('ttl'):
payload['ttl'] = address['ttl']
print('Attempting to update record...')
resp = call_dyn(suffix,method='put',data=payload)
if resp['msgs'][0]['INFO'] == 'id: You did not reference a specific record':
error('Unable to update record. Check spelling or try --cname?')
publish(config['zone'])
def delete_record(address):
'''
Delete a record. Requires a dict that with dict['delete'] and dict['value'].
Optionally is dict['cname'] (True/None) if the record is a cname.
Be very careful and ensure this is what you want to do.
'''
if not address['delete']:
error('Missing first argument.')
if address['cname']:
suffix = "CNAMERecord/%s/%s/" % (address['zone'], address['delete'])
else:
suffix = "ARecord/%s/%s/" % (address['zone'], address['delete'])
print("Attempting to delete record: %s" % address['delete'])
resp = call_dyn(suffix,method='delete')
print resp['msgs'][0]['INFO']
if resp['msgs'][0]['INFO'] == 'delete: 0 records deleted':
if not address['cname']:
error('No records deleted. Check spelling or try toggling --cname?')
publish(config['zone'])
def end_session(token):
'''
Delete the existing session. Requires a token. This prevents further changes
from being made with the created session token.
'''
suffix = 'Session/'
# Squelch these lines if we are printing a CSV format
if not config['list']:
print('Ending current session...')
call_dyn(suffix,method='delete')
exit()
if __name__ == '__main__':
verify_credentials()
config['token'] = get_token(config)
if config['list']:
for record in list_records():
print record
elif config['create']:
create_record(config)
elif config['update_record']:
update_record(config)
elif config['delete']:
delete_record(config)
else:
error('No arguments provided.')
end_session(config['token'])