forked from Linuxfabrik/lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net3.py
281 lines (234 loc) · 7.57 KB
/
net3.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
#! /usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.rst
"""Provides network related functions and variables.
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2023022101'
import random
import re
import socket
try:
import netifaces
HAVE_NETIFACES = True
except ImportError:
HAVE_NETIFACES = False
from . import txt3 # pylint: disable=C0413
from . import url3 # pylint: disable=C0413
# address family
AF_INET = socket.AF_INET # 2
AF_INET6 = getattr(socket, 'AF_INET6', object()) # 10
AF_UNSPEC = socket.AF_UNSPEC # any kind of connection
try:
AF_UNIX = socket.AF_UNIX
except AttributeError:
# If the AF_UNIX constant is not defined then this protocol is unsupported.
AF_UNIX = None
# socket type
SOCK_TCP = socket.SOCK_STREAM # 1
SOCK_UDP = socket.SOCK_DGRAM # 2
SOCK_RAW = socket.SOCK_RAW
# protocol type
PROTO_TCP = socket.IPPROTO_TCP # 6
PROTO_UDP = socket.IPPROTO_UDP # 17
PROTO_IP = socket.IPPROTO_IP # 0
PROTO_MAP = {
# address family, socket type: proto
(AF_INET, socket.SOCK_STREAM): 'tcp',
(AF_INET, socket.SOCK_DGRAM): 'udp',
(AF_INET6, socket.SOCK_DGRAM): 'udp6',
(AF_INET6, socket.SOCK_STREAM): 'tcp6',
}
FAMILIYSTR = {
# as defined in Python's socketmodule.c
0: 'unspec',
1: 'unix',
2: '4', # inet
3: 'ax25',
4: 'ipx',
5: 'appletalk',
6: 'netrom',
7: 'bridge',
8: 'atmpvc',
9: 'x25',
10: '6', # inet6
11: 'rose',
12: 'decnet',
13: 'netbeui',
14: 'security',
15: 'key',
16: 'route',
17: 'packet',
18: 'ash',
19: 'econet',
20: 'atmsvc',
22: 'sna',
23: 'irda',
24: 'pppox',
25: 'wanpipe',
26: 'llc',
30: 'tipc',
31: 'bluetooth',
}
PROTOSTR = {
# as defined in Python's socketmodule.c
0: 'ip',
1: 'icmp',
2: 'igmp',
6: 'tcp',
8: 'egp',
12: 'pup',
17: 'udp',
22: 'idp',
41: 'ipv6',
43: 'routing',
44: 'fragment',
50: 'esp',
51: 'ah',
58: 'icmpv6',
59: 'none',
60: 'dstopts',
103: 'pim',
255: 'raw',
}
SOCKETSTR = {
# as defined in Python's socketmodule.c
1: 'tcp', # stream
2: 'udp', # dgram
3: 'raw',
4: 'rdm',
5: 'seqpacket',
}
FQDN_REGEX = re.compile(
r"^((?!-)[-A-Z\d]{1,63}(?<!-)\.)+(?!-)[-A-Z\d]{1,63}(?<!-)\.?$", re.IGNORECASE
)
def fetch(host, port, msg=None, timeout=3, ipv6=False):
"""Fetch data via a TCP/IP socket connection. You may optionally send a msg first.
Supports both IPv4 and IPv6.
Taken from https://docs.python.org/3/library/socket.html, enhanced.
"""
try:
if ipv6:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(int(timeout))
s.connect((host, int(port)))
except:
return (False, 'Could not open socket.')
if msg is not None:
try:
s.sendall(msg)
except:
return (False, 'Could not send payload "{}".'.format(msg))
fragments = []
while True:
try:
chunk = s.recv(1024)
if not chunk:
break
fragments.append(txt3.to_text(chunk))
except socket.timeout as e:
# non-blocking behavior via a time out with socket.settimeout(n)
err = e.args[0]
# this next if/else is a bit redundant, but illustrates how the
# timeout exception is setup
if err == 'timed out':
return (False, 'Socket timed out.')
return (False, 'Can\'t fetch data: {}'.format(e))
except socket.error as e:
# Something else happened, handle error, exit, etc.
return (False, 'Can\'t fetch data: {}'.format(e))
try:
s.close()
except:
s = None
return (True, ''.join(fragments))
def get_netinfo():
if HAVE_NETIFACES:
# Update stats using the netifaces lib
try:
default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
except (KeyError, AttributeError):
return []
stats = {}
try:
stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
stats['mask_cidr'] = ip_to_cidr(stats['mask'])
stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
except (KeyError, AttributeError):
return []
stats['public_address'] = None
try:
stats['public_address'] = get_ip_public()
except:
return []
return stats
def get_public_ip(services):
"""Retrieve the public IP address from a list of online services.
The list of "what is my ip" services is shuffled before being used. The first service
returning an IP "wins".
>>> get_public_ip('https://ipv4.icanhazip.com,https://ipecho.net/plain,https://ipinfo.io/ip')
1.2.3.4
"""
if not services:
return (False, None)
services = services.split(',')
random.shuffle(services)
ip = None
for url in services:
success, ip = url3.fetch(url.strip(), timeout=2)
if success and ip:
ip = ip.strip()
try:
return (True, txt3.to_text(ip))
except:
return (True, ip)
return (False, ip)
def is_valid_hostname(hostname):
"""True for a validated fully-qualified domain name (FQDN), in full
compliance with RFC 1035, and the "preferred form" specified in RFC
3686 s. 2, whether relative or absolute.
If and only if the FQDN ends with a dot (in place of the RFC1035
trailing null byte), it may have a total length of 254 bytes, still it
must be less than 253 bytes.
https://tools.ietf.org/html/rfc3696#section-2
https://tools.ietf.org/html/rfc1035
from https://github.com/ypcrts/fqdn/blob/develop/fqdn
"""
length = len(hostname)
if hostname.endswith("."):
length -= 1
if length > 253:
return False
return bool(FQDN_REGEX.match(hostname))
def is_valid_relative_hostname(hostname):
"""True for a fully-qualified domain name (FQDN) that is RFC
preferred-form compliant and ends with a `.`.
With relative FQDNS in DNS lookups, the current hosts domain name or
search domains may be appended.
from https://github.com/ypcrts/fqdn/blob/develop/fqdn
"""
return hostname.endswith(".") and is_valid_hostname(hostname)
def is_valid_absolute_hostname(hostname):
"""True for a validated fully-qualified domain name that compiles with the
RFC preferred-form and does not end with a `.`.
from https://github.com/ypcrts/fqdn/blob/develop/fqdn
"""
return not hostname.endswith(".") and is_valid_hostname(hostname)
def netmask_to_cidr(ip):
"""Convert IP address to CIDR.
>>> netmask_to_cdir('255.255.255.0')
24
"""
# Thanks to @Atticfire
# See https://github.com/nicolargo/glances/issues/1417#issuecomment-469894399
if ip is None:
return 0
return sum(bin(int(x)).count('1') for x in ip.split('.'))