-
Notifications
You must be signed in to change notification settings - Fork 1
/
madmac.py
271 lines (227 loc) · 6.79 KB
/
madmac.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
import argparse
import random
import re
class UnsupportedOperation(Exception):
"""
Exception class for unsupported operations.
"""
pass
def extract_alphanumeric(value):
"""
Extract alphanumeric values from given string.
:param value:
:return:
"""
pattern = re.compile(r"[\W_]+")
return pattern.sub("", value)
def pair_hexvalue(value, delimiter=":"):
"""
Pair hex values (string) using delimiter.
e.g. abcdef -> ab:cd:ef
:param value:
:param delimiter:
:return:
"""
return delimiter.join(
["{}{}".format(a, b) for a, b in zip(value[::2], value[1::2])]
)
def int_to_hexstr(value, _format="{:06x}"):
"""
Convert int to hex string.
:param value:
:param _format:
:return:
"""
if not isinstance(value, int):
raise ValueError("Required int.")
return _format.format(value)
def hexstr_to_int(value, base=16):
"""
Convert hex string to int.
:param value:
:param base:
:return:
"""
return int(value, base=base)
def access_object_member(value, member_name, *args, **kwargs):
"""
Handle accessing object built-in members (properties and functions).
:param value:
:param member_name:
:param args:
:param kwargs:
:return:
"""
if hasattr(value, member_name):
member = getattr(value, member_name)
if callable(member):
return member(*args, **kwargs)
return member
else:
raise UnsupportedOperation(
"Unsupported operation for {}: {}".format(value, member_name)
)
def validate_3octets(value):
"""
Validate 3-octets string.
:param value:
:return:
"""
is_valid = False
try:
is_valid = int(value, base=16) >= 0 and len(value) == 6
except ValueError:
is_valid = False
except TypeError:
is_valid = False
return is_valid
def validate_mac(value):
"""
Validate MAC address.
:param value: EUI-48 MAC address
:return:
"""
is_valid = False
try:
cleaned = extract_alphanumeric(value)
is_valid = hexstr_to_int(cleaned) >= 0
except ValueError:
is_valid = False
except TypeError:
is_valid = False
return is_valid
class MacGenerator(object):
"""
Class to generate EUI-48 MAC Addresses.
"""
# NOTE: 0 = 000000
min_3octet_int = 0
# NOTE: 16777215 = ffffff
max_3octet_int = 16777215
def __init__(
self,
oui=None,
start=None,
stop=None,
total=1,
delimiter=":",
case="lower",
):
"""
:param oui: 6-digit organizationally unique identifier
:param start: NIC specific start address
:param stop: NIC specific end address
:param total: Total number to generate
:param delimiter: Delimiter for MAC address
:param case: Use lower or upper
"""
self.oui = oui
self.start = start
self.i_start = 0 # integer value of "start"
self.stop = stop
self.i_stop = 0 # integer value of "stop"
self.total = total
self.delimiter = delimiter
self.case = case
def normalize_oui(self):
"""
Normalize OUI by using delimiter.
:return:
"""
cleaned = extract_alphanumeric(self.oui)
return pair_hexvalue(cleaned, delimiter=self.delimiter)
def _pick_random_int(self):
return random.randint(self.min_3octet_int, self.max_3octet_int)
def _prepare_oui(self):
if not self.oui:
self.oui = int_to_hexstr(self._pick_random_int())
else:
self.oui = extract_alphanumeric(self.oui)
if not validate_3octets(self.oui):
raise ValueError("Invalid OUI value.")
def _prepare_start_address(self):
if not self.start:
self.i_start = self._pick_random_int()
else:
self.start = extract_alphanumeric(self.start)
if not validate_3octets(self.start):
raise ValueError("Invalid value for starting address.")
else:
self.i_start = hexstr_to_int(self.start)
def _prepare_stop_address(self):
if not self.stop:
is_valid_total = (
self.total
and access_object_member(self.total, "real")
and self.total >= 0
)
if not is_valid_total:
raise ValueError("Invalid value for total.")
else:
self.i_stop = self.i_start + self.total
else:
if not self.start:
raise ValueError(
"Invalid usage. Use -s along with -r together."
)
self.stop = extract_alphanumeric(self.stop)
if not validate_3octets(self.stop):
raise ValueError("Invalid value for ending address.")
else:
self.i_stop = hexstr_to_int(self.stop)
def _validate(self):
"""
Validate input values. If no input values provided, values will be
generated automatically.
"""
self._prepare_oui()
self._prepare_start_address()
self._prepare_stop_address()
def _build(self):
"""
Build generator object.
:return:
"""
self.oui = self.normalize_oui()
for each in range(self.i_start, self.i_stop):
dev_id = pair_hexvalue(
int_to_hexstr(each), delimiter=self.delimiter
)
generated_mac = "{oui}{delimiter}{dev}".format(
oui=self.oui, delimiter=self.delimiter, dev=dev_id
)
yield access_object_member(generated_mac, self.case)
def generate(self):
"""
Generate EUI-48 MAC addresses.
:return:
"""
self._validate()
return self._build()
def handle_args():
parser = argparse.ArgumentParser(
description="MAC address generator library for testers.",
argument_default=argparse.SUPPRESS,
)
parser.add_argument(
"-o", "--oui", help="6-digit organizationally unique identifier"
)
parser.add_argument("-r", "--start", help="NIC specific start address")
parser.add_argument("-s", "--stop", help="NIC specific end address")
parser.add_argument(
"-t", "--total", type=int, default=1, help="Number of MACs to generate"
)
parser.add_argument(
"-d", "--delimiter", default=":", help="Delimiter for MAC address"
)
parser.add_argument(
"-c", "--case", default="lower", help="Use lower or upper"
)
return parser
def main(args):
macg = MacGenerator(**args)
return "\n".join(list(macg.generate()))
if __name__ == "__main__":
parser = handle_args()
args = vars(parser.parse_args())
print(main(args))