-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.py
160 lines (114 loc) · 5.68 KB
/
example.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
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
example.py - 2011.11.09
Author : Alexandre Norman - [email protected]
Contributor: Steve 'Ashcrow' Milner - [email protected]
Licence : GPL v3 or any later version
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import os
import nmap # import nmap.py module
try:
nm = nmap.PortScanner() # instantiate nmap.PortScanner object
except nmap.PortScannerError:
print('Nmap not found', sys.exc_info()[0])
sys.exit(1)
except:
print("Unexpected error:", sys.exc_info()[0])
sys.exit(1)
nm.scan('127.0.0.1', '22-443') # scan host 127.0.0.1, ports from 22 to 443
nm.command_line() # get command line used for the scan : nmap -oX - -p 22-443 127.0.0.1
nm.scaninfo() # get nmap scan informations {'tcp': {'services': '22-443', 'method': 'connect'}}
nm.all_hosts() # get all hosts that were scanned
nm['127.0.0.1'].hostname() # get hostname for host 127.0.0.1
nm['127.0.0.1'].state() # get state of host 127.0.0.1 (up|down|unknown|skipped)
nm['127.0.0.1'].all_protocols() # get all scanned protocols ['tcp', 'udp'] in (ip|tcp|udp|sctp)
if ('tcp' in nm['127.0.0.1']):
list(nm['127.0.0.1']['tcp'].keys()) # get all ports for tcp protocol
nm['127.0.0.1'].all_tcp() # get all ports for tcp protocol (sorted version)
nm['127.0.0.1'].all_udp() # get all ports for udp protocol (sorted version)
nm['127.0.0.1'].all_ip() # get all ports for ip protocol (sorted version)
nm['127.0.0.1'].all_sctp() # get all ports for sctp protocol (sorted version)
if nm['127.0.0.1'].has_tcp(22): # is there any information for port 22/tcp on host 127.0.0.1
nm['127.0.0.1']['tcp'][22] # get infos about port 22 in tcp on host 127.0.0.1
nm['127.0.0.1'].tcp(22) # get infos about port 22 in tcp on host 127.0.0.1
nm['127.0.0.1']['tcp'][22]['state'] # get state of port 22/tcp on host 127.0.0.1 (open
# a more usefull example :
for host in nm.all_hosts():
print('----------------------------------------------------')
print('Host : {0} ({1})'.format(host, nm[host].hostname()))
print('State : {0}'.format(nm[host].state()))
for proto in nm[host].all_protocols():
print('----------')
print('Protocol : {0}'.format(proto))
lport = list(nm[host][proto].keys())
lport.sort()
for port in lport:
print('port : {0}\tstate : {1}'.format(port, nm[host][proto][port]))
print('----------------------------------------------------')
# print result as CSV
print(nm.csv())
print('----------------------------------------------------')
# If you want to do a pingsweep on network 192.168.1.0/24:
nm.scan(hosts='192.168.0.0/24', arguments='-n -sP -PE -PA21,23,80,3389')
hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
for host, status in hosts_list:
print('{0}:{1}'.format(host, status))
print('----------------------------------------------------')
# Asynchronous usage of PortScannerAsync
nma = nmap.PortScannerAsync()
def callback_result(host, scan_result):
print('------------------')
print(host, scan_result)
nma.scan(hosts='192.168.0.0/30', arguments='-sP', callback=callback_result)
while nma.still_scanning():
print("Waiting ...")
nma.wait(2) # you can do whatever you want but I choose to wait after the end of the scan
if (os.getuid() == 0):
print('----------------------------------------------------')
# Os detection (need root privileges)
nm.scan("127.0.0.1", arguments="-O")
if 'osclass' in nm['127.0.0.1']:
for osclass in nm['127.0.0.1']['osclass']:
print('OsClass.type : {0}'.format(osclass['type']))
print('OsClass.vendor : {0}'.format(osclass['vendor']))
print('OsClass.osfamily : {0}'.format(osclass['osfamily']))
print('OsClass.osgen : {0}'.format(osclass['osgen']))
print('OsClass.accuracy : {0}'.format(osclass['accuracy']))
print('')
if 'osmatch' in nm['127.0.0.1']:
for osmatch in nm['127.0.0.1']['osmatch']:
print('OsMatch.name : {0}'.format(osclass['name']))
print('OsMatch.accuracy : {0}'.format(osclass['accuracy']))
print('OsMatch.line : {0}'.format(osclass['line']))
print('')
if 'fingerprint' in nm['127.0.0.1']:
print('Fingerprint : {0}'.format(nm['127.0.0.1']['fingerprint']))
# Vendor list for MAC address
nm.scan('192.168.0.0/24', arguments='-O')
for h in nm.all_hosts():
if 'mac' in nm[h]['addresses']:
print(nm[h]['addresses'], nm[h]['vendor'])
print('----------------------------------------------------')
# Read output captured to a file
# Example : nmap -oX - -p 22-443 -sV 127.0.0.1 > nmap_output.xml
with open("./nmap_output.xml", "r") as fd:
content = fd.read()
nm.analyse_nmap_xml_scan(content)
print(nm.csv())
print('----------------------------------------------------')
# Progressive scan with generator
nm = nmap.PortScannerYield()
for progressive_result in nm.scan('127.0.0.1/24', '22-25'):
print(progressive_result)