nmap (version 0.7.1)
index
/home/xael/ESPACE_KM/python/python-nmap/nmap/nmap.py

nmap.py - version and date, see below
 
Source code : https://bitbucket.org/xael/python-nmap
 
Author :
 
* Alexandre Norman - norman at xael.org
 
Contributors:
 
* Steve 'Ashcrow' Milner - steve at gnulinux.net
* Brian Bustin - brian at bustin.us
* old.schepperhand
* Johan Lundberg
* Thomas D. maaaaz
* Robert Bost
* David Peltier
* Ed Jones
 
Licence: GPL v3 or any later version for python-nmap
 
 
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/>.
 
 
**************
IMPORTANT NOTE
**************
 
The Nmap Security Scanner used by python-nmap is distributed
under it's own licence that you can find at https://svn.nmap.org/nmap/COPYING
 
Any redistribution of python-nmap along with the Nmap Security Scanner
must conform to the Nmap Security Scanner licence

 
Modules
       
xml.etree.ElementTree
csv
io
os
re
shlex
subprocess
sys

 
Classes
       
builtins.Exception(builtins.BaseException)
PortScannerError
PortScannerTimeout
builtins.dict(builtins.object)
PortScannerHostDict
builtins.object
PortScanner
PortScannerAsync
PortScannerYield

 
class PortScanner(builtins.object)
    PortScanner(nmap_search_path=('nmap', '/usr/bin/nmap', '/usr/local/bin/nmap', '/sw/bin/nmap', '/opt/local/bin/nmap'))
 
PortScanner class allows to use nmap from python
 
  Methods defined here:
__getitem__(self, host)
returns a host detail
__init__(self, nmap_search_path=('nmap', '/usr/bin/nmap', '/usr/local/bin/nmap', '/sw/bin/nmap', '/opt/local/bin/nmap'))
Initialize PortScanner module
 
* detects nmap on the system and nmap version
* may raise PortScannerError exception if nmap is not found in the path
 
:param nmap_search_path: tupple of string where to search for nmap executable.
                         Change this if you want to use a specific version of nmap.
:returns: nothing
all_hosts(self)
returns a sorted list of all hosts
analyse_nmap_xml_scan(self, nmap_xml_output=None, nmap_err='', nmap_err_keep_trace='', nmap_warn_keep_trace='')
Analyses NMAP xml scan ouput
 
May raise PortScannerError exception if nmap output was not xml
 
Test existance of the following key to know if something went wrong : ['nmap']['scaninfo']['error']
If not present, everything was ok.
 
:param nmap_xml_output: xml string to analyse
:returns: scan_result as dictionnary
command_line(self)
returns command line used for the scan
 
may raise AssertionError exception if called before scanning
csv(self)
returns CSV output as text
 
Example :
host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe
127.0.0.1;localhost;PTR;tcp;22;ssh;open;OpenSSH;protocol 2.0;syn-ack;5.9p1 Debian 5ubuntu1;10;cpe
127.0.0.1;localhost;PTR;tcp;23;telnet;closed;;;conn-refused;;3;
127.0.0.1;localhost;PTR;tcp;24;priv-mail;closed;;;conn-refused;;3;
get_nmap_last_output(self)
Returns the last text output of nmap in raw text
this may be used for debugging purpose
 
:returns: string containing the last text output of nmap in raw text
has_host(self, host)
returns True if host has result, False otherwise
listscan(self, hosts='127.0.0.1')
do not scan but interpret target hosts and return a list a hosts
nmap_version(self)
returns nmap version if detected (int version, int subversion)
or (0, 0) if unknown
:returns: (nmap_version_number, nmap_subversion_number)
scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', sudo=False, timeout=0)
Scan given hosts
 
May raise PortScannerError exception if nmap output was not xml
 
Test existance of the following key to know
if something went wrong : ['nmap']['scaninfo']['error']
If not present, everything was ok.
 
:param hosts: string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
:param ports: string for ports as nmap use it '22,53,110,143-4564'
:param arguments: string of arguments for nmap '-sU -sX -sC'
:param sudo: launch nmap with sudo if True
:param timeout: int, if > zero, will terminate scan after seconds, otherwise will wait indefintely
 
:returns: scan_result as dictionnary
scaninfo(self)
returns scaninfo structure
{'tcp': {'services': '22', 'method': 'connect'}}
 
may raise AssertionError exception if called before scanning
scanstats(self)
returns scanstats structure
{'uphosts': '3', 'timestr': 'Thu Jun  3 21:45:07 2010', 'downhosts': '253', 'totalhosts': '256', 'elapsed': '5.79'}  # NOQA: E501
 
may raise AssertionError exception if called before scanning

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class PortScannerAsync(builtins.object)
    PortScannerAsync allows to use nmap from python asynchronously
for each host scanned, callback is called with scan result for the host
 
  Methods defined here:
__del__(self)
Cleanup when deleted
__init__(self)
Initialize the module
 
* detects nmap on the system and nmap version
* may raise PortScannerError exception if nmap is not found in the path
scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', callback=None, sudo=False, timeout=0)
Scan given hosts in a separate process and return host by host result using callback function
 
PortScannerError exception from standard nmap is catched and you won't know about but get None as scan_data
 
:param hosts: string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
:param ports: string for ports as nmap use it '22,53,110,143-4564'
:param arguments: string of arguments for nmap '-sU -sX -sC'
:param callback: callback function which takes (host, scan_data) as arguments
:param sudo: launch nmap with sudo if true
:param timeout: int, if > zero, will terminate scan after seconds, otherwise will wait indefintely
still_scanning(self)
:returns: True if a scan is currently running, False otherwise
stop(self)
Stop the current scan process
wait(self, timeout=None)
Wait for the current scan process to finish, or timeout
 
:param timeout: default = None, wait timeout seconds

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
class PortScannerError(builtins.Exception)
    PortScannerError(value)
 
Exception error class for PortScanner class
 
 
Method resolution order:
PortScannerError
builtins.Exception
builtins.BaseException
builtins.object

Methods defined here:
__init__(self, value)
Initialize self.  See help(type(self)) for accurate signature.
__repr__(self)
Return repr(self).
__str__(self)
Return str(self).

Data descriptors defined here:
__weakref__
list of weak references to the object (if defined)

Static methods inherited from builtins.Exception:
__new__(*args, **kwargs) from builtins.type
Create and return a new object.  See help(type) for accurate signature.

Methods inherited from builtins.BaseException:
__delattr__(self, name, /)
Implement delattr(self, name).
__getattribute__(self, name, /)
Return getattr(self, name).
__reduce__(...)
Helper for pickle.
__setattr__(self, name, value, /)
Implement setattr(self, name, value).
__setstate__(...)
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.

Data descriptors inherited from builtins.BaseException:
__cause__
exception cause
__context__
exception context
__dict__
__suppress_context__
__traceback__
args

 
class PortScannerHostDict(builtins.dict)
    Special dictionnary class for storing and accessing host scan result
 
 
Method resolution order:
PortScannerHostDict
builtins.dict
builtins.object

Methods defined here:
all_ip(self)
:returns: list of ip ports
all_protocols(self)
:returns: a list of all scanned protocols
all_sctp(self)
:returns: list of sctp ports
all_tcp(self)
:returns: list of tcp ports
all_udp(self)
:returns: list of udp ports
has_ip(self, port)
:param port: (int) ip port
:returns: True if ip port has info, False otherwise
has_sctp(self, port)
:returns: True if sctp port has info, False otherwise
has_tcp(self, port)
:param port: (int) tcp port
:returns: True if tcp port has info, False otherwise
has_udp(self, port)
:param port: (int) udp port
:returns: True if udp port has info, False otherwise
hostname(self)
For compatibility purpose...
:returns: try to return the user record or the first hostname of the list hostnames
hostnames(self)
:returns: list of hostnames
ip(self, port)
:param port: (int) ip port
:returns: info for ip port
sctp(self, port)
:returns: info for sctp port
state(self)
:returns: host state
tcp(self, port)
:param port: (int) tcp port
:returns: info for tpc port
udp(self, port)
:param port: (int) udp port
:returns: info for udp port
uptime(self)
:returns: host state

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

Methods inherited from builtins.dict:
__contains__(self, key, /)
True if the dictionary has the specified key, else False.
__delitem__(self, key, /)
Delete self[key].
__eq__(self, value, /)
Return self==value.
__ge__(self, value, /)
Return self>=value.
__getattribute__(self, name, /)
Return getattr(self, name).
__getitem__(...)
x.__getitem__(y) <==> x[y]
__gt__(self, value, /)
Return self>value.
__init__(self, /, *args, **kwargs)
Initialize self.  See help(type(self)) for accurate signature.
__ior__(self, value, /)
Return self|=value.
__iter__(self, /)
Implement iter(self).
__le__(self, value, /)
Return self<=value.
__len__(self, /)
Return len(self).
__lt__(self, value, /)
Return self<value.
__ne__(self, value, /)
Return self!=value.
__or__(self, value, /)
Return self|value.
__repr__(self, /)
Return repr(self).
__reversed__(self, /)
Return a reverse iterator over the dict keys.
__ror__(self, value, /)
Return value|self.
__setitem__(self, key, value, /)
Set self[key] to value.
__sizeof__(...)
D.__sizeof__() -> size of D in memory, in bytes
clear(...)
D.clear() -> None.  Remove all items from D.
copy(...)
D.copy() -> a shallow copy of D
get(self, key, default=None, /)
Return the value for key if key is in the dictionary, else default.
items(...)
D.items() -> a set-like object providing a view on D's items
keys(...)
D.keys() -> a set-like object providing a view on D's keys
pop(...)
D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 
If key is not found, default is returned if given, otherwise KeyError is raised
popitem(self, /)
Remove and return a (key, value) pair as a 2-tuple.
 
Pairs are returned in LIFO (last-in, first-out) order.
Raises KeyError if the dict is empty.
setdefault(self, key, default=None, /)
Insert key with a value of default if key is not in the dictionary.
 
Return the value for key if key is in the dictionary, else default.
update(...)
D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
In either case, this is followed by: for k in F:  D[k] = F[k]
values(...)
D.values() -> an object providing a view on D's values

Class methods inherited from builtins.dict:
__class_getitem__(...) from builtins.type
See PEP 585
fromkeys(iterable, value=None, /) from builtins.type
Create a new dictionary with keys from iterable and values set to value.

Static methods inherited from builtins.dict:
__new__(*args, **kwargs) from builtins.type
Create and return a new object.  See help(type) for accurate signature.

Data and other attributes inherited from builtins.dict:
__hash__ = None

 
class PortScannerTimeout(PortScannerError)
    PortScannerTimeout(value)
 

 
 
Method resolution order:
PortScannerTimeout
PortScannerError
builtins.Exception
builtins.BaseException
builtins.object

Methods inherited from PortScannerError:
__init__(self, value)
Initialize self.  See help(type(self)) for accurate signature.
__repr__(self)
Return repr(self).
__str__(self)
Return str(self).

Data descriptors inherited from PortScannerError:
__weakref__
list of weak references to the object (if defined)

Static methods inherited from builtins.Exception:
__new__(*args, **kwargs) from builtins.type
Create and return a new object.  See help(type) for accurate signature.

Methods inherited from builtins.BaseException:
__delattr__(self, name, /)
Implement delattr(self, name).
__getattribute__(self, name, /)
Return getattr(self, name).
__reduce__(...)
Helper for pickle.
__setattr__(self, name, value, /)
Implement setattr(self, name, value).
__setstate__(...)
with_traceback(...)
Exception.with_traceback(tb) --
set self.__traceback__ to tb and return self.

Data descriptors inherited from builtins.BaseException:
__cause__
exception cause
__context__
exception context
__dict__
__suppress_context__
__traceback__
args

 
class PortScannerYield(PortScannerAsync)
    PortScannerYield allows to use nmap from python with a generator
for each host scanned, yield is called with scan result for the host
 
 
Method resolution order:
PortScannerYield
PortScannerAsync
builtins.object

Methods defined here:
__init__(self)
Initialize the module
 
* detects nmap on the system and nmap version
* may raise PortScannerError exception if nmap is not found in the path
scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', sudo=False, timeout=0)
Scan given hosts in a separate process and return host by host result using callback function
 
PortScannerError exception from standard nmap is catched and you won't know about it
 
:param hosts: string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
:param ports: string for ports as nmap use it '22,53,110,143-4564'
:param arguments: string of arguments for nmap '-sU -sX -sC'
:param callback: callback function which takes (host, scan_data) as arguments
:param sudo: launch nmap with sudo if true
:param timeout: int, if > zero, will terminate scan after seconds, otherwise will wait indefintely
still_scanning(self)
:returns: True if a scan is currently running, False otherwise
stop(self)
Stop the current scan process
wait(self, timeout=None)
Wait for the current scan process to finish, or timeout
 
:param timeout: default = None, wait timeout seconds

Methods inherited from PortScannerAsync:
__del__(self)
Cleanup when deleted

Data descriptors inherited from PortScannerAsync:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

 
Functions
       
__scan_progressive__(self, hosts, ports, arguments, callback, sudo, timeout)
Used by PortScannerAsync for callback
convert_nmap_output_to_encoding(value, code='ascii')
Change encoding for scan_result object from unicode to whatever
 
:param value: scan_result as dictionnary
:param code: default = "ascii", encoding destination
 
:returns: scan_result as dictionnary with new encoding

 
Data
        __last_modification__ = '2021.10.26'

 
Author
        Alexandre Norman (norman@xael.org)