-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcomm_net.py
88 lines (64 loc) · 2.42 KB
/
comm_net.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
import os
import platform
from comm import Comm
import dns.resolver
import subprocess
# TODO spravit z toho staticku metodu classy CommNet
def getCommType():
return {"net": (CommNet, checkNet, __name__)}
class CommNet(Comm):
def __init__(self, host):
super().__init__(host)
# raise NotImplementedError
def __enter__(self):
raise NotImplementedError
def __exit__(self, *args):
raise NotImplementedError
def read(self, size):
raise NotImplementedError
def write(self, what):
raise NotImplementedError
def checkNet(hosts, good, conflict, wrong):
loc_hosts = hosts[:] # make a copy
for host in loc_hosts:
remote_device = host['host_commdev']
result = ping(remote_device)
if result is False:
wrong.append(host)
print('%s %s can\'t ping host' % (host['host_name'], remote_device))
loc_hosts.remove(host) # do not take hosts we cannot ping
check_net_IP_duplicities(loc_hosts, good, conflict, wrong)
def check_net_IP_duplicities(hosts, good, conflict, wrong):
resolver = dns.resolver.Resolver()
resolver.timeout = 1 # 1 seconds time out if no response to avoid long waiting
ip_for_hosts = dict() # mapping IP address -> host
for host in hosts:
net_address = host['host_commdev']
# store dns lookups for each host separately
try:
answer = resolver.query(net_address)
except dns.exception.DNSException:
print('%s %s can\'t open connection' % (host['host_name'], net_address))
wrong.append(host)
else:
addr_set = set(rdata.address for rdata in answer)
for addres in addr_set: #store mapping IP -> list of hosts
ip_for_hosts.setdefault(addres, []).append(host)
# here add conflict hosts into conflicts
for host_list in ip_for_hosts.values():
if len(host_list) > 1:
conflict.extend(host_list)
else:
good.extend(host_list)
# TODO spravit z toho staticku metodu classy CommNet
def ping(host):
"""
Returns True if host responds to a ping request
"""
try:
# call ping with 1 packet, waiting 1 second if no response, with no output at all
subprocess.run(['ping', '-c 1', '-W 1', host], stdout=None, stderr=None, check=True)
except subprocess.CalledProcessError:
return False
else:
return True