-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib_lan.py
124 lines (103 loc) · 3.04 KB
/
lib_lan.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
import sys
sys.dont_write_bytecode = True # No '*.pyc' precompiled files
from rich import print
import os
import iptools
import ipaddress
from netaddr import IPAddress, IPNetwork
from ipaddress import ip_network, IPv4Network
from ipaddress import (AddressValueError, NetmaskValueError)
import re
def validate_subnet(ip):
'''
Validates subnet address, with or without mask bits.
Both examples are valid:
'10.10.10.0'
'10.10.10.0/24'
Return: (bool):
'''
result = True
try:
ipaddress.ip_network(ip, strict=False)
except (ValueError):
result = False
return result
def validate_ip(ip):
'''
Validates IP address, no mask eg:
'10.10.10.0' is valid
'10.10.10.0/24' is not valid
Return: (bool):
'''
result = True
try:
ipaddress.IPv4Address(ip)
except ipaddress.AddressValueError:
result = False
return result
def validate_netmask(netmask):
netmask = str(netmask)
result = False
if validate_ip(netmask) is True:
result = iptools.ipv4.validate_netmask(netmask)
return result
def check_sn_bc(ip, subnet):
'''Check if provided IP address
is not the IP of the subnet itself or broadcast.
Returns:
exit_code (str/None):
'''
if IPAddress(ip) == IPAddress(subnet.network):
exit_code = 'eq_net'
elif IPAddress(ip) == subnet.broadcast:
exit_code = 'eq_broadcast'
else:
exit_code = None
return exit_code
def subnet_with_bits(ip, netmask):
'''
ARGS:
ip (str): IP address in x.x.x.x format.
Eg.: '10.10.10.1'
netmask (str): Netmask address in x.x.x.x format.
Eg.: '255.255.255.0'
RETURN:
subnet (str): Subnet address in the format of IP/bits notation.
Eg.: '10.10.10.0/24'
'''
subnet = str(ip_network(ip + '/' + netmask, strict=False))
return subnet
def ip_from_net_addr(net_addr):
'''
ARGS:
net_addr (str): Subnet address in one of these form:
10.10.10.10/255.255.0.0
172.16.2.1/24
RETURNS:
ip (str): IP address of the network, where the input IP is.
Eg for the input are the examples above the results will be:
10.10.0.0
172.16.2.0
'''
subnet = str(IPv4Network(net_addr, strict=False).network_address)
return subnet
def maskbits_from_net_addr(net_addr):
'''
ARGS:
net_addr (str): Subnet address in one of these form:
10.10.10.10/255.255.0.0
172.16.2.1/24
RETURNS:
maskbits (str): netmask converted to bits.
Eg:
the result maskbits = 24
if the octet netmask is: 255.255.255.0
'''
maskbits = str(
IPAddress(str(IPv4Network(net_addr, strict=False).netmask)).netmask_bits()
)
return maskbits
def main():
print('This is the lan library.')
if __name__ == '__main__':
main()