-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathauto-discover.py
More file actions
90 lines (66 loc) · 2.19 KB
/
auto-discover.py
File metadata and controls
90 lines (66 loc) · 2.19 KB
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
import csv
import paramiko
def read_hosts(filename):
with open(filename) as f:
lines = f.read().splitlines()
return lines
def scan(nm):
devices = []
for host in nm.all_hosts():
device = {}
device['name'] = host
device['state'] = nm[host].state()
for proto in nm[host].all_protocols():
device['ssh'] = nm[host][proto][22]['state']
snmp = have_snmp(str(host))
if snmp:
device['snmp'] = 'open'
else:
device['snmp'] = 'closed'
devices.append(device)
return devices
def have_snmp(host):
load("SNMPv2-MIB")
try:
m = M(host=host, community="public", version=2)
if m.sysName is not None:
snmp = True
except:
snmp = False
return snmp
def check_ssh(self, ip, user, key_file, initial_wait=0, interval=0, retries=1):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sleep(initial_wait)
for x in range(retries):
try:
ssh.connect(ip, username=user, key_filename=key_file)
return True
except (BadHostKeyException, AuthenticationException,
SSHException, socket.error) as e:
print e
sleep(interval)
except Exception, e:
print e
sleep(interval)
return False
def write_to_csv(devices, filename):
filename = filename.split("/")[0].replace(".", "_") + ".csv"
with open(filename, 'wb') as discover_file:
fieldnames = ["name", "state", "snmp", "ssh"]
writer = csv.DictWriter(discover_file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(devices)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Discover info of network' +
'devices.')
parser.add_argument('inputfile', help='file with hosts to scan')
parser.add_argument('outputfile', help='csv file to write devices info')
args = parser.parse_args()
hosts_to_scan = read_hosts(args.inputfile)
hosts_str = " ".join(hosts_to_scan)
# Scan hosts
nm = nmap.PortScanner()
nm.scan(hosts_str, '22')
devices = scan(nm)
write_to_csv(devices, args.outputfile)