-
Notifications
You must be signed in to change notification settings - Fork 7
/
host.py
2902 lines (2434 loc) · 86.9 KB
/
host.py
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ipaddress
import typing
from .cli import Flag, cli
from .dhcp import assoc_mac_to_ip
from .exceptions import HostNotFoundWarning
from .history import history
from .history_log import get_history_items, print_history_items
from .log import cli_error, cli_info, cli_warning
from .util import (
clean_hostname,
cname_exists,
convert_wildcard_to_regex,
delete,
first_unused_ip_from_network,
format_mac,
get,
get_info_by_name,
get_list,
get_network,
get_network_by_ip,
get_network_reserved_ips,
host_info_by_name,
host_info_by_name_or_ip,
ip_in_mreg_net,
is_valid_email,
is_valid_ip,
is_valid_ipv4,
is_valid_ipv6,
is_valid_mac,
is_valid_network,
is_valid_ttl,
patch,
post,
resolve_input_name,
)
#################################
# Add the main command 'host' #
#################################
host = cli.add_command(
prog='host',
description='Manage hosts.',
short_desc='Manage hosts',
)
def print_hinfo(hinfo: dict, padding: int = 14) -> None:
"""Pretty given hinfo id"""
if hinfo is None:
return
print("{1:<{0}}cpu={2} os={3}".format(padding, "Hinfo:", hinfo['cpu'], hinfo['os']))
def zoneinfo_for_hostname(host: str) -> dict:
"""Return zoneinfo for a hostname, or None if not found or invalid"""
if "." not in host:
return None
path = f"/api/v1/zones/forward/hostname/{host}"
history.record_get(path)
zoneinfo = get(path, ok404=True)
return None if zoneinfo is None else zoneinfo.json()
def check_zone_for_hostname(name: str, force: bool, require_zone: bool = False):
# Require force if FQDN not in MREG zone
zoneinfo = zoneinfo_for_hostname(name)
if zoneinfo is None:
if require_zone:
cli_warning(f"{name} isn't in a zone controlled by MREG.")
if not force:
cli_warning(f"{name} isn't in a zone controlled by MREG, must force")
elif 'delegation' in zoneinfo and not force:
delegation = zoneinfo['delegation']['name']
cli_warning(f"{name} is in zone delegation {delegation}, must force")
def _get_ip_from_args(ip, force, ipversion=None):
# Try to fail fast for valid IP
if ipversion is not None and is_valid_ip(ip):
if ipversion == 4:
# Fail if input isn't ipv4
if is_valid_ipv6(ip):
cli_warning("got ipv6 address, want ipv4.")
if not is_valid_ipv4(ip):
cli_warning(f"not valid ipv4 address: {ip}")
elif ipversion == 6:
# Fail if input isn't ipv6
if is_valid_ipv4(ip):
cli_warning("got ipv4 address, want ipv6.")
if not is_valid_ipv6(ip):
cli_warning(f"not valid ipv6 address: {ip}")
# Handle arbitrary ip from network if received a network w/o mask
if ip.endswith("/"):
network = get_network(ip[:-1])
ip = first_unused_ip_from_network(network)
# Handle arbitrary ip from network if received a network w/mask
elif is_valid_network(ip):
network = get_network(ip)
ip = first_unused_ip_from_network(network)
elif is_valid_ip(ip):
path = "/api/v1/hosts/"
hosts = get_list(path, params={"ipaddresses__ipaddress": ip})
if hosts and not force:
hostnames = ','.join([i['name'] for i in hosts])
cli_warning(f'{ip} already in use by: {hostnames}. Must force')
network = get_network_by_ip(ip)
if not network:
if force:
return ip
cli_warning(f"{ip} isn't in a network controlled by MREG, must force")
else:
cli_warning(f"Could not determine network for {ip}")
network_object = ipaddress.ip_network(network['network'])
if ipversion:
if network_object.version != ipversion:
if ipversion == 4:
cli_warning("Attemptet to get an ipv4 address, but input yielded ipv6")
elif ipversion == 6:
cli_warning("Attemptet to get an ipv6 address, but input yielded ipv4")
if network["frozen"] and not force:
cli_warning("network {} is frozen, must force"
.format(network["network"]))
# Chat the address given isn't reserved
reserved_addresses = get_network_reserved_ips(network['network'])
if ip in reserved_addresses and not force:
cli_warning("Address is reserved. Requires force")
if network_object.num_addresses > 2:
if ip == network_object.network_address.exploded:
cli_warning("Can't overwrite the network address of the network")
if ip == network_object.broadcast_address.exploded:
cli_warning("Can't overwrite the broadcast address of the network")
return ip
def _check_ipversion(ip, ipversion):
# Ip sanity check
if ipversion == 4:
if not is_valid_ipv4(ip):
cli_warning(f'not a valid ipv4: {ip}')
elif ipversion == 6:
if not is_valid_ipv6(ip):
cli_warning(f'not a valid ipv6: {ip}')
else:
cli_warning(f'Unknown ipversion: {ipversion}')
################################################################################
# #
# Host manipulation #
# #
################################################################################
#########################################
# Implementation of sub command 'add' #
#########################################
def add(args):
"""Add a new host with the given name.
ip/network, comment and contact are optional.
"""
# Fail if given host exists
name = clean_hostname(args.name)
try:
name = resolve_input_name(name)
except HostNotFoundWarning:
pass
else:
cli_warning("host {} already exists".format(name))
if "*" in name and not args.force:
cli_warning("Wildcards must be forced.")
check_zone_for_hostname(name, args.force)
if cname_exists(name):
cli_warning("the name is already in use by a cname")
if args.ip:
ip = _get_ip_from_args(args.ip, args.force)
# Contact sanity check
if args.contact and not is_valid_email(args.contact):
cli_warning(
"invalid mail address ({}) when trying to add {}".format(
args.contact,
args.name))
# Create the new host with an ip address
path = "/api/v1/hosts/"
data = {
"name": name,
"contact": args.contact or None,
"comment": args.comment or None,
}
if args.ip:
data['ipaddress'] = ip
history.record_post(path, resource_name=name, new_data=data)
post(path, **data)
if args.macaddress is not None:
# It can only be one, as it was just created.
ipdata = get(f"{path}{name}").json()['ipaddresses'][0]
assoc_mac_to_ip(args.macaddress, ipdata, force=args.force)
msg = f"created host {name}"
if args.ip:
msg += f" with IP {ip}"
cli_info(msg, print_msg=True)
# Add 'add' as a sub command to the 'host' command
host.add_command(
prog='add',
description='Add a new host with the given name, ip or network and contact. '
'comment is optional.',
short_desc='Add a new host',
callback=add,
flags=[
Flag('name',
short_desc='Name of new host (req)',
description='Name of new host (req)'),
Flag('-ip',
short_desc='An ip or net',
description="The hosts ip or a network. If it's a network the first free IP is "
"selected from the network",
metavar='IP/NET'),
Flag('-contact',
short_desc='Contact mail for the host',
description='Contact mail for the host'),
Flag('-comment',
short_desc='A comment.',
description='A comment.'),
Flag('-macaddress',
description='Mac address',
metavar='MACADDRESS'),
Flag('-force',
action='store_true',
description='Enable force.'),
]
)
############################################
# Implementation of sub command 'remove' #
############################################
def remove(args):
# args.name, args.force
"""Remove host."""
# Get host info or raise exception
info = host_info_by_name_or_ip(args.name)
warn_msg = ""
# Require force if host has any cnames.
cnames = info["cnames"]
if len(cnames):
if not args.force:
warn_msg += "{} cnames. ".format(len(cnames))
# Require force if host has multiple A/AAAA records
if len(info["ipaddresses"]) > 1 and not args.force:
warn_msg += "{} ipaddresses. ".format(len(info["ipaddresses"]))
# Require force if host has any NAPTR records. Delete the NAPTR records if
# force
path = "/api/v1/naptrs/"
history.record_get(path)
naptrs = get_list(path, params={"host": info['id']})
if len(naptrs) > 0:
if not args.force:
warn_msg += "{} NAPTR records. ".format(len(naptrs))
else:
for naptr in naptrs:
cli_info("deleted NAPTR record {} when removing {}".format(
naptr["replacement"],
info["name"],
))
# Require force if host has any SRV records. Delete the SRV records if force
path = "/api/v1/srvs/"
history.record_get(path)
srvs = get_list(path, params={"host__name": info['name']})
if len(srvs) > 0:
if not args.force:
warn_msg += "{} SRV records. ".format(len(srvs))
else:
for srv in srvs:
cli_info("deleted SRV record {} when removing {}".format(
srv["name"],
info["name"],
))
# Require force if host has any PTR records. Delete the PTR records if force
if len(info["ptr_overrides"]) > 0:
if not args.force:
warn_msg += "{} PTR records. ".format(len(info["ptr_overrides"]))
else:
for ptr in info["ptr_overrides"]:
cli_info("deleted PTR record {} when removing {}".format(
ptr["ipaddress"],
info["name"],
))
# To be able to undo the delete the ipaddress field of the 'old_data' has to
# be an ipaddress string
if len(info["ipaddresses"]) > 0:
info["ipaddress"] = info["ipaddresses"][0]["ipaddress"]
# Warn user and raise exception if any force requirements was found
if warn_msg:
cli_warning("{} has: {}Must force".format(info["name"], warn_msg))
# Delete host
path = f"/api/v1/hosts/{info['name']}"
history.record_delete(path, old_data=info)
delete(path)
cli_info("removed {}".format(info["name"]), print_msg=True)
# Add 'remove' as a sub command to the 'host' command
host.add_command(
prog='remove',
description='Remove the given host.',
callback=remove,
flags=[
Flag('name',
short_desc='Name or ip.',
description='Name of host or an ip belonging to the host.',
metavar='NAME/IP'),
Flag('-force',
action='store_true',
description='Enable force.'),
]
)
##########################################
# Implementation of sub command 'info' #
##########################################
# first some print helpers
def print_host_name(name: str, padding: int = 14) -> None:
"""Pretty print given name."""
if name is None:
return
assert isinstance(name, str)
print("{1:<{0}}{2}".format(padding, "Name:", name))
def print_contact(contact: str, padding: int = 14) -> None:
"""Pretty print given contact."""
if contact is None:
return
assert isinstance(contact, str)
print("{1:<{0}}{2}".format(padding, "Contact:", contact))
def print_comment(comment: str, padding: int = 14) -> None:
"""Pretty print given comment."""
if comment is None:
return
assert isinstance(comment, str)
print("{1:<{0}}{2}".format(padding, "Comment:", comment))
def print_ipaddresses(ipaddresses: typing.Iterable[dict], names: bool = False,
padding: int = 14) -> None:
"""Pretty print given ip addresses"""
def _find_padding(lst, attr):
return max(padding, max([len(i[attr]) for i in lst])+1)
if not ipaddresses:
return
a_records = []
aaaa_records = []
len_ip = _find_padding(ipaddresses, 'ipaddress')
for record in ipaddresses:
if is_valid_ipv4(record["ipaddress"]):
a_records.append(record)
elif is_valid_ipv6(record["ipaddress"]):
aaaa_records.append(record)
if names:
len_names = _find_padding(ipaddresses, 'name')
else:
len_names = padding
for records, text in ((a_records, 'A_Records'), (aaaa_records, 'AAAA_Records')):
if records:
print("{1:<{0}}{2:<{3}} {4}".format(len_names, text, "IP", len_ip, "MAC"))
for record in records:
ip = record["ipaddress"]
mac = record["macaddress"]
if names:
name = record["name"]
else:
name = ""
print("{1:<{0}}{2:<{3}} {4}".format(
len_names, name, ip if ip else "<not set>", len_ip,
mac if mac else "<not set>"))
def print_ttl(ttl: int, padding: int = 14) -> None:
"""Pretty print given ttl"""
assert isinstance(ttl, int) or ttl is None
print("{1:<{0}}{2}".format(padding, "TTL:", ttl or "(Default)"))
def print_loc(loc: dict, padding: int = 14) -> None:
"""Pretty print given loc"""
if loc is None:
return
assert isinstance(loc, dict)
print("{1:<{0}}{2}".format(padding, "Loc:", loc['loc']))
def print_cname(cname: str, host: str, padding: int = 14) -> None:
"""Pretty print given cname"""
print("{1:<{0}}{2} -> {3}".format(padding, "Cname:", cname, host))
def print_mx(mxs: dict, padding: int = 14) -> None:
"""Pretty print all MXs"""
if not mxs:
return
len_pri = len("Priority")
print("{1:<{0}}{2} {3}".format(padding, "MX:", "Priority", "Server"))
for mx in sorted(mxs, key=lambda i: i['priority']):
print("{1:<{0}}{2:>{3}} {4}".format(padding, "", mx['priority'], len_pri, mx['mx']))
def print_naptr(naptr: dict, host_name: str, padding: int = 14) -> None:
"""Pretty print given txt"""
assert isinstance(naptr, dict)
assert isinstance(host_name, str)
def print_ptr(ip: str, host_name: str, padding: int = 14) -> None:
"""Pretty print given txt"""
assert isinstance(ip, str)
assert isinstance(host_name, str)
print("{1:<{0}}{2} -> {3}".format(padding, 'PTR override:', ip, host_name))
def print_txt(txt: str, padding: int = 14) -> None:
"""Pretty print given txt"""
if txt is None:
return
assert isinstance(txt, str)
print("{1:<{0}}{2}".format(padding, "TXT:", txt))
def print_bacnetid(bacnetid: dict, padding: int = 14) -> None:
"""Pretty print given txt"""
if bacnetid is None:
return
assert isinstance(bacnetid, dict)
print("{1:<{0}}{2}".format(padding, "BACnet ID:", bacnetid['id']))
def _print_host_info(info):
# Pretty print all host info
print_host_name(info["name"])
print_contact(info["contact"])
if info["comment"]:
print_comment(info["comment"])
print_ipaddresses(info["ipaddresses"])
for ptr in info["ptr_overrides"]:
print_ptr(ptr["ipaddress"], info["name"])
print_ttl(info["ttl"])
print_mx(info['mxs'])
print_hinfo(info['hinfo'])
if info["loc"]:
print_loc(info["loc"])
for cname in info["cnames"]:
print_cname(cname["name"], info["name"])
for txt in info["txts"]:
print_txt(txt["txt"])
_srv_show(host_id=info['id'])
_naptr_show(info)
_sshfp_show(info)
if "bacnetid" in info:
print_bacnetid(info.get("bacnetid"))
cli_info("printed host info for {}".format(info["name"]))
def _print_ip_info(ip):
"""Print all hosts which have a given IP. Also print out PTR override, if any."""
path = "/api/v1/hosts/"
params = {
"ipaddresses__ipaddress": ip,
"ordering": "name",
}
ip = ip.lower()
history.record_get(path)
hosts = get_list(path, params=params)
ipaddresses = []
ptrhost = None
for info in hosts:
for i in info['ipaddresses']:
if i['ipaddress'] == ip:
i['name'] = info['name']
ipaddresses.append(i)
for i in info['ptr_overrides']:
if i['ipaddress'] == ip:
ptrhost = info['name']
print_ipaddresses(ipaddresses, names=True)
if len(ipaddresses) > 1 and ptrhost is None:
cli_warning(f'IP {ip} used by {len(ipaddresses)} hosts, but no PTR override')
if ptrhost is None:
path = "/api/v1/hosts/"
params = {
"ptr_overrides__ipaddress": ip,
}
history.record_get(path)
hosts = get_list(path, params=params)
if hosts:
ptrhost = hosts[0]['name']
elif ipaddresses:
ptrhost = 'default'
if not ipaddresses and ptrhost is None:
cli_warning(f'Found no hosts or ptr override matching IP {ip}')
print_ptr(ip, ptrhost)
def info_(args):
"""Print information about host. If <name> is an alias the cname hosts info
is shown.
"""
for name_or_ip in args.hosts:
# Get host info or raise exception
if is_valid_ip(name_or_ip):
_print_ip_info(name_or_ip)
elif is_valid_mac(name_or_ip):
mac = format_mac(name_or_ip)
ret = get_list("api/v1/hosts/", params={"ipaddresses__macaddress": mac})
if ret:
_print_host_info(ret[0])
else:
cli_warning(f'Found no host with macaddress: {mac}')
else:
info = host_info_by_name(name_or_ip)
name = clean_hostname(name_or_ip)
if any(cname['name'] == name for cname in info['cnames']):
print(f'{name} is a CNAME for {info["name"]}')
_print_host_info(info)
# Add 'info' as a sub command to the 'host' command
host.add_command(
prog='info',
description='Print info about one or more hosts.',
short_desc='Print info about one or more hosts.',
callback=info_,
flags=[
Flag('hosts',
description='One or more hosts given by their name, ip or mac.',
short_desc='One or more names, ips or macs.',
nargs='+',
metavar='NAME/IP/MAC')
]
)
def find(args):
"""List hosts maching search criteria
"""
def _add_param(param, value):
if '*' not in value:
value = f'*{value}*'
param, value = convert_wildcard_to_regex(param, value)
params[param] = value
if not any([args.name, args.comment, args.contact]):
cli_warning('Need at least one search critera')
params = {
"ordering": "name",
"page_size": 1,
}
for param in ('contact', 'comment', 'name'):
value = getattr(args, param)
if value:
_add_param(param, value)
path = "/api/v1/hosts/"
ret = get(path, params=params).json()
if ret['count'] == 0:
cli_warning('No hosts found.')
elif ret['count'] > 500:
cli_warning(f'Too many hits, {ret["count"]}, more than limit of 500. Refine search.')
del(params["page_size"])
ret = get_list(path, params=params)
max_name = max_contact = 20
for i in ret:
max_name = max(max_name, len(i['name']))
max_contact = max(max_contact, len(i['contact']))
def _print(name, contact, comment):
print("{0:<{1}} {2:<{3}} {4}".format(name, max_name, contact, max_contact, comment))
_print('Name', 'Contact', 'Comment')
for i in ret:
_print(i['name'], i['contact'], i['comment'])
host.add_command(
prog='find',
description='Lists hosts matching search criteria',
short_desc='Lists hosts matching search criteria',
callback=find,
flags=[
Flag('-name',
description='Name or part of name',
short_desc='Name or part of name',
metavar='NAME'),
Flag('-comment',
description='Comment or part of comment',
short_desc='Comment or part of comment',
metavar='CONTACT'),
Flag('-contact',
description='Contact or part of contact',
short_desc='Contact or part of contact',
metavar='CONTACT')
]
)
############################################
# Implementation of sub command 'rename' #
############################################
def rename(args):
"""Rename host. If <old-name> is an alias then the alias is renamed.
"""
# Find old host
old_name = resolve_input_name(args.old_name)
# Make sure new hostname does not exist.
new_name = clean_hostname(args.new_name)
try:
new_name = resolve_input_name(new_name)
except HostNotFoundWarning:
pass
else:
if not args.force:
cli_warning("host {} already exists".format(new_name))
if cname_exists(new_name):
cli_warning("the name is already in use by a cname")
# Require force if FQDN not in MREG zone
check_zone_for_hostname(new_name, args.force)
if "*" in new_name and not args.force:
cli_warning("Wildcards must be forced.")
old_data = {"name": old_name}
new_data = {"name": new_name}
# Rename host
path = f"/api/v1/hosts/{old_name}"
# Cannot redo/undo now since it changes name
history.record_patch(path, new_data, old_data, redoable=False,
undoable=False)
patch(path, name=new_name)
cli_info("renamed {} to {}".format(old_name, new_name), print_msg=True)
# Add 'rename' as a sub command to the 'host' command
host.add_command(
prog='rename',
description='Rename host. If the old name is an alias then the alias is '
'renamed.',
short_desc='Rename a host',
callback=rename,
flags=[
Flag('old_name',
description='Host name of the host to rename. May be an alias. '
'If it is an alias then the alias is renamed.',
short_desc='Existing host name.',
metavar='OLD'),
Flag('new_name',
description='New name for the host, or alias.',
short_desc='New name',
metavar='NEW'),
Flag('-force',
action='store_true',
description='Enable force.'),
],
)
#################################################
# Implementation of sub command 'set_comment' #
#################################################
def set_comment(args):
"""Set comment for host. If <name> is an alias the cname host is updated.
"""
# Get host info or raise exception
info = host_info_by_name(args.name)
old_data = {"comment": info["comment"] or ""}
new_data = {"comment": args.comment}
# Update comment
path = f"/api/v1/hosts/{info['name']}"
history.record_patch(path, new_data, old_data)
patch(path, comment=args.comment)
cli_info("Updated comment of {} to \"{}\""
.format(info["name"], args.comment), print_msg=True)
# Add 'set_comment' as a sub command to the 'host' command
host.add_command(
prog='set_comment',
description='Set comment for host. If NAME is an alias the cname host is '
'updated.',
short_desc='Set comment.',
callback=set_comment,
flags=[
Flag('name',
description='Name of the target host.',
metavar='NAME'),
Flag('comment',
description='The new comment. If it contains spaces then it must '
'be enclosed in quotes.',
metavar='COMMENT')
],
)
#################################################
# Implementation of sub command 'set_contact' #
#################################################
def set_contact(args):
"""Set contact for host. If <name> is an alias the cname host is updated.
"""
# Contact sanity check
if not is_valid_email(args.contact):
cli_warning("invalid mail address {} (target host: {})".format(
args.contact, args.name))
# Get host info or raise exception
info = host_info_by_name(args.name)
old_data = {"contact": info["contact"]}
new_data = {"contact": args.contact}
# Update contact information
path = f"/api/v1/hosts/{info['name']}"
history.record_patch(path, new_data, old_data)
patch(path, contact=args.contact)
cli_info("Updated contact of {} to {}".format(info["name"], args.contact),
print_msg=True)
# Add 'set_contact' as a sub command to the 'host' command
host.add_command(
prog='set_contact',
description='Set contact for host. If NAME is an alias the cname host is '
'updated.',
short_desc='Set contact.',
callback=set_contact,
flags=[
Flag('name',
description='Name of the target host.',
metavar='NAME'),
Flag('contact',
description='Mail address of the contact.',
metavar='CONTACT')
],
)
################################################################################
# #
# A records #
# #
################################################################################
def _ip_add(args, ipversion, macaddress=None):
info = None
if "*" in args.name and not args.force:
cli_warning("Wildcards must be forced.")
ip = _get_ip_from_args(args.ip, args.force, ipversion=ipversion)
try:
# Get host info for or raise exception
info = host_info_by_name(args.name)
except HostNotFoundWarning:
pass
if macaddress is not None:
if is_valid_mac(macaddress):
macaddress = format_mac(macaddress)
else:
cli_error(f"Invalid macaddress: {macaddress}")
if info is None:
hostname = clean_hostname(args.name)
data = {'name': hostname,
'ipaddress': ip}
# Create new host with IP
path = "/api/v1/hosts/"
history.record_post(path, ip, data)
post(path, **data)
cli_info(f"Created host {hostname} with ip {ip}", print_msg=True)
if macaddress is not None:
# It can only be one, as it was just created.
ip = get(f"{path}{hostname}").json()['ipaddresses'][0]
assoc_mac_to_ip(macaddress, ip, force=args.force)
else:
# Require force if host has multiple A/AAAA records
if len(info["ipaddresses"]) and not args.force:
cli_warning("{} already has A/AAAA record(s), must force"
.format(info["name"]))
if any(args.ip == i["ipaddress"] for i in info["ipaddresses"]):
cli_warning(f"Host already has IP {args.ip}")
data = {
"host": info["id"],
"ipaddress": ip,
}
if macaddress is not None:
data['macaddress'] = macaddress
# Add IP
path = "/api/v1/ipaddresses/"
history.record_post(path, ip, data)
post(path, **data)
cli_info(f"added ip {ip} to {info['name']}", print_msg=True)
###########################################
# Implementation of sub command 'a_add' #
###########################################
def a_add(args):
"""Add an A record to host. If <name> is an alias the cname host is used.
"""
_ip_add(args, 4, macaddress=args.macaddress)
# Add 'a_add' as a sub command to the 'host' command
host.add_command(
prog='a_add',
description='Add an A record to host. If NAME is an alias the cname host '
'is used.',
short_desc='Add A record.',
callback=a_add,
flags=[
Flag('name',
description='Name of the target host.',
metavar='NAME'),
Flag('ip',
description='The IP of new A record. May also be a network, '
'in which case a random IP address from that network '
'is chosen.',
metavar='IP/network'),
Flag('-macaddress',
description='Mac address',
metavar='MACADDRESS'),
Flag('-force',
action='store_true',
description='Enable force.'),
],
)
##############################################
# Implementation of sub command 'a_change' #
##############################################
def _ip_change(args, ipversion):
if args.old == args.new:
cli_warning("New and old IP are equal")
_check_ipversion(args.old, ipversion)
# Get host info or raise exception
info = host_info_by_name(args.name)
for i in info["ipaddresses"]:
if i["ipaddress"] == args.old:
ip_id = i["id"]
break
else:
cli_warning("\"{}\" is not owned by {}".format(args.old, info["name"]))
new_ip = _get_ip_from_args(args.new, args.force, ipversion=ipversion)
old_data = {"ipaddress": args.old}
new_data = {"ipaddress": new_ip}
# Update A/AAAA records ip address
path = f"/api/v1/ipaddresses/{ip_id}"
# Cannot redo/undo since recourse name changes
history.record_patch(path, new_data, old_data, redoable=False,
undoable=False)
patch(path, ipaddress=new_ip)
cli_info(
"changed ip {} to {} for {}".format(args.old, new_ip, info["name"]),
print_msg=True)
def a_change(args):
"""Change A record. If <name> is an alias the cname host is used.
"""
_ip_change(args, 4)
# Add 'a_change' as a sub command to the 'host' command
host.add_command(
prog='a_change',
description='Change an A record for the target host. If NAME is an alias '
'the cname host is used.',
short_desc='Change A record.',
callback=a_change,
flags=[
Flag('name',
description='Name of the target host.',
short_desc='Host name.',
metavar='NAME'),
Flag('-old',
description='The existing IP that should be changed.',
short_desc='IP to change.',
required=True,
metavar='IP'),
Flag('-new',
description='The new IP address. May also be a network, in which '
'case a random IP from that network is chosen.',
short_desc='New IP.',
required=True,
metavar='IP/network'),
Flag('-force',
action='store_true',
description='Enable force.'),
],
)
############################################
# Implementation of sub command 'a_move' #
############################################
def _ip_move(args, ipversion):
_check_ipversion(args.ip, ipversion)
frominfo = host_info_by_name(args.fromhost)
toinfo = host_info_by_name(args.tohost)
ip_id = None
for ip in frominfo['ipaddresses']:
if ip['ipaddress'] == args.ip:
ip_id = ip['id']
ptr_id = None
for ptr in frominfo['ptr_overrides']:
if ptr['ipaddress'] == args.ip:
ptr_id = ptr['id']
if ip_id is None and ptr_id is None:
cli_warning(f'Host {frominfo["name"]} have no IP or PTR with address {args.ip}')
msg = ""
if ip_id:
path = f'/api/v1/ipaddresses/{ip_id}'
patch(path, host=toinfo['id'])
msg = f'Moved ipaddress {args.ip}'
else:
msg += f'No ipaddresses matched. '
if ptr_id:
path = f'/api/v1/ptroverrides/{ptr_id}'
patch(path, host=toinfo['id'])
msg += 'Moved PTR override.'
cli_info(msg, print_msg=True)
def a_move(args):
"""Move an IP from a host to another host. Will move also move the PTR, if any.
"""
_ip_move(args, 4)