Giter Club home page Giter Club logo

nmmapper / python3-nmap Goto Github PK

View Code? Open in Web Editor NEW
269.0 5.0 74.0 157 KB

A python 3 library which helps in using nmap port scanner. This is done by converting each nmap command into a callable python3 method or function. System administrators can now automatic nmap scans using python

Home Page: https://www.nmmapper.com/sys/networkmapper/nmap/online-port-scanning/

License: GNU General Public License v3.0

Python 99.79% Shell 0.21%
portscanner nmap network-scanner subdomain-finder service-discovery osint nmmapper nmap-scanning nmap-command nmap-port-scanner

python3-nmap's People

Contributors

almohress avatar begimher avatar ced2142 avatar cldhms avatar davidromanovizc avatar daytona675 avatar dbbegimh avatar dupouyleo avatar f-froehlich avatar ioncodes avatar josh-thurston avatar jpseara avatar latest-release avatar lesinigo avatar mrenergy64 avatar mykings avatar nmmapper avatar priyambajpai22 avatar r5mtf avatar sebasanblas avatar suyashnepal avatar ybstark avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

python3-nmap's Issues

Docker Compose Issue

I can't seem to get this to work in a docker container. For some reason, Nmap seems to think every IP address is on the network (when it's not). No issues when running outside of the docker container.

This is what I've got so far. https://github.com/charlesomer/network-devices-scanner

I've set network_mode: host in the compose file so I'm not sure. I may have missed something obvious?

parse_noportscan does not parse mac address

I'm trying to use this package to find the IP, knowing the MAC address, but...
This data:

<host><status state="up" reason="arp-response" reason_ttl="0"/>
<address addr="10.11.12.13" addrtype="ipv4"/>
<address addr="00:01:02:03:04:05" addrtype="mac" vendor="Vendor Inc."/>
<hostnames>
<hostname name="00-01-02-03-04-05-dns-inc.com" type="PTR"/>
</hostnames>
<times srtt="1000" rttvar="5000" to="100000"/>
</host>

Is only parsed as:

{'state': 'up', 'reason': 'arp-response', 'reason_ttl': '0', 'addr': '10.11.12.13', 'addrtype': 'ipv4'}

Can't tell when a request timed out

Hello!

First of all thank you for this fantastic tool.

I have noted that it is nearly impossible to detect a timeout in your libraries. I even tried to add -v and there's nothing in the output.

Here's my call:

nmap_version_detection(target_ip, args="-Pn --script vulners -p80 --host-timeout 5 -v")

There's nothing in the output that allows me to know if it timed out. Even when I know it did time out, it will just output whatever info it grabbed till then, and the summary says we are good:

'summary': 'Nmap done at Tue Oct 11 01:33:53 2022; 1 IP address '
                        '(1 host up) scanned in 23.91 seconds',

If I run the same command in BASH, I can grep for "timed out" if I use -v:

$ sudo /usr/bin/nmap -oX - -O -sV -Pn --host-timeout 5 192.168.122.51 -p80 --script vulners -v | grep timed

<taskend task="Service scan" time="1665448215" extrainfo="1 host timed out"/>

It seems like you are not parsing this in your libraries.

Is there any way for me to know if a timeout happened when using your library?

This is really important in order to understand if the command actually worked or not.

Mac address value null

The macaddress value is null in the returned json object. The following code will give a null value in the returned json object:

import nmap3
if __name__ == "__main__":
    nmap = nmap3.Nmap()
    result = nmap.nmap_os_detection("192.168.1.1")
    print(result)

Prints the following (only the mac address atribute):
"macaddress": null

TypeError: scan_command() got an unexpected keyword argument 'arg'

When I try to call OS detection, I get the error below:

os_deteccao = nmap.nmap_os_detection(ip)
File "C:\Python38\lib\site-packages\nmap3\nmap3.py", line 206, in nmap_os_detection
xml_root = self.scan_command(target=target, arg=arg, args=args)
TypeError: scan_command() got an unexpected keyword argument 'arg'

Mininet Virtual Host

Hi there,
I'm trying to use your library in a virtual host created in Mininet, I ran my Python3 file and it reported "No module named 'nmap3' ", yet your library worked well outside of the host. I wonder if it is available for virtual hosts in Mininet

Error in host discovery functions (arp vs dns disabled)

Hi,

First of all, thank you for this great work. It helps me a lot, thank you.

I think you've mixed up the two functions. Indeed in the arp_discovery you call disable_dns stuff while you do the opposite in disable_dns function.
Please check the words between the stars in the below code from the nmap3.py file.

def nmap_***arp_discovery***(self, host, args=None):
       """
       Scan host using the nmap tcp connect
       @cmd nmap ***-n*** 192.168.178.1
       """
       parser  = NmapCommandParser(None)

       if(args):
           assert(isinstance(args, str)), "Expected string got {0} instead".format(type(args))

       scancommand = " {host} {default}".format(host=host, default=***self.disable_dns***)
       scan_command = self.default_command() + scancommand
       if(args):
           scan_command += " {0}".format(args)
       scan_shlex = shlex.split(scan_command) # prepare it

       # Use the top_port_parser
       output = self.run_command(scan_shlex)
       xml_root = self.get_xml_et(output)
       tcp_results = parser.filter_top_ports(xml_root)
       return tcp_results

   def nmap_***disable_dns***(self, host, args=None):
       """
       Scan host using the nmap tcp connect
       @cmd nmap ***-PR*** 192.168.178.1
       """
       parser  = NmapCommandParser(None)

       if(args):
           assert(isinstance(args, str)), "Expected string got {0} instead".format(type(args))

       scancommand = " {host} {default}".format(host=host, default=***self.arp_discovery***)
       scan_command = self.default_command() + scancommand
       if(args):
           scan_command += " {0}".format(args)
       scan_shlex = shlex.split(scan_command) # prepare it
...

Function not handling additional args

Hi,

Trying options: -O --osscan-guess -p 5432 not resulting with the expected data when combined with no_ping scan as below:

nmd.nmap_portscan_only(target, args=scan_type)

Same command from the command line works well and the OS is guessed:

nmap -oX - -Pn -O --osscan-guess -p 5432 127.0.0.1

Please see the result executing your function:

 {
    "127.0.0.1": [
        {
            "host": "127.0.0.1",
            "portid": "5432",
            "protocol": "tcp",
            "reason": "syn-ack",
            "reason_ttl": "64",
            "service": {
                "conf": "3",
                "method": "table",
                "name": "postgresql"
            },
            "state": "open"
        }
    ],
    "runtime": {
        "elapsed": "3.99",
        "exit": "success",
        "summary": "Nmap done at Sun May 24 13:16:08 2020; 1 IP address (1 host up) scanned in 3.99 seconds",
        "time": "1590322568",
        "timestr": "Sun May 24 13:16:08 2020"
    },
    "stats": {
        "args": "/usr/local/bin/nmap -oX - -Pn -O --osscan-guess -p 5432 127.0.0.1",
        "scanner": "nmap",
        "start": "1590322565",
        "startstr": "Sun May 24 13:16:05 2020",
        "version": "7.80",
        "xmloutputversion": "1.04"
    }
}

Move documentation requirements

sphinx is only required for generating documentation.
Most people will not generate the documentation and therefore don't need it.
I think the sphinx dependencies should be moved to a file like requirements-dev.txt or similar.

nmap_dns_brute_script doesn't work properly

When I run nmap.nmap_dns_brute_script("google.com") a few times it will eventually get the hostname and address wrong.
Expected:

[{'address': '172.217.168.46', 'hostname': 'admin.google.com'},...

What I get sometimes:

[{'address': 'admin.google.com', 'hostname': '172.217.168.46'},...

callback_progress

Hi
I have a feature in mind. It is to have a "callback_progress" that displays its progress whenever a function is executed.

EX:

>>> def print_status(i):
           print(str(i))

>>> import nmap3
>>> nmap = nmap3.Nmap()
>>> nmap.nmap_version_detection("your-host.com", callback_progress=print_status)
10%
30%
90%
100%
[...]

wrong handling of xml.etreeElementTree objects

This library has code like this in multiple places:

if (some_xml_element.find('something_else')):
    do_some_stuff

Under some Python / xml.etree versions this will not work as intended, for example I am getting this output from Nmap().nmap_version_detection() (notice missing information about port state and service exposed on the port):

{'port': '443',
 'protocol': 'tcp'}

In the case of Nmap().nmap_version_detection() this happens because <state> and <service> do not have any further sub-elements and as the docs say:

Elements with no subelements will test as False. This behavior will change in future versions. Use specific len(elem) or elem is None test instead.

Changing if(port.find("service")): with if port.find("service") is not None: will restore correct behaviour and give complete results like:

 {'port': '443',
  'protocol': 'tcp',
  'reason': 'syn-ack',
  'reason_ttl': '0',
  'service': {'conf': '10',
              'devicetype': 'security-misc',
              'method': 'probed',
              'name': 'http',
              'product': 'Fortinet security device httpd',
              'tunnel': 'ssl'},
  'state': 'open'}]

UDP Scan without root cause exceptions

I'm running the code as the following:
nmap = nmap3.NmapScanTechniques() report = nmap.nmap_udp_scan(HOST, '--top-ports 1000')

It cause the exception:
`
You requested a scan type which requires root privileges.
QUITTING!
Traceback (most recent call last):
File "/home/fabian/.local/lib/python3.8/site-packages/nmap3/nmap3.py", line 261, in get_xml_et
return ET.fromstring(command_output)
File "/usr/lib/python3.8/xml/etree/ElementTree.py", line 1321, in XML
return parser.close()
xml.etree.ElementTree.ParseError: no element found: line 1, column 0

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "./check_open_ports.py", line 36, in
OpenPorts()
File "/home/fabian/monitoring-utils/monitoring_utils/Checks/NMAP/OpenPorts.py", line 48, in init
Plugin.init(self, 'Check DNSSEC status')
File "/home/fabian/monitoring-utils/monitoring_utils/Core/Plugin/Plugin.py", line 51, in init
self.run()
File "/home/fabian/monitoring-utils/monitoring_utils/Checks/NMAP/OpenPorts.py", line 66, in run
self.check_ports()
File "/home/fabian/monitoring-utils/monitoring_utils/Checks/NMAP/OpenPorts.py", line 70, in check_ports
report, report = self.__executor.scan()
File "/home/fabian/monitoring-utils/monitoring_utils/Core/Executor/NMAPExecutor.py", line 62, in scan
return self.scan_top_ports()
File "/home/fabian/monitoring-utils/monitoring_utils/Core/Executor/NMAPExecutor.py", line 74, in scan_top_ports
udp_host_result, udp_runtime, udp_stats = self.scan_udp()
File "/home/fabian/monitoring-utils/monitoring_utils/Core/Executor/NMAPExecutor.py", line 112, in scan_udp
report = nmap.nmap_udp_scan(self.__host, self.get_args())
File "/home/fabian/.local/lib/python3.8/site-packages/nmap3/nmap3.py", line 369, in nmap_udp_scan
xml_root = self.scan_command(self.udp_scan, target=target, args=args)
File "/home/fabian/.local/lib/python3.8/site-packages/nmap3/nmap3.py", line 316, in scan_command
xml_root = self.get_xml_et(output)
File "/home/fabian/.local/lib/python3.8/site-packages/nmap3/nmap3.py", line 262, in get_xml_et
except xml.etree.ElementTree.ParseError:
NameError: name 'xml' is not defined
`

First of all it cause because Nmap.run_command() does not check the command output for errors. I expect to get an exception or a valid json like

{
'runtime': {
'time': 'XX',
'timestr': 'XX',
'elapsed': 'XX',
'summary': 'require root privileges',
'exit': 'failure'
},
'stats': {
'scanner': 'nmap',
'args': '/usr/bin/nmap -oX - -sT --top-ports 1000 192.168.0.10',
'start': 'XX',
'startstr': 'XX',
'version': 'XX',
'xmloutputversion': 'XX'
}
}

Furthermore xou don't check the output in Nmap.scan_command() If there was an regular error (like above) you should not parse the XML output. Also the exception handling in Nmap.get_xml_et() is wrong because xml.etree.ElementTree.ParseError sould be ParseError instead.

Best whishes

Fabian Fröhlich

Monitoring the progress of the scans

Hi,
I am looking for a method to have the progress of the scans either every x seconds or in an interactive way.
nmap has the argument --stats-every 10s which allows to display its stats, is there a way to get the stdout of the nmap command?

Thank,

Nmap -sV -T3

Hello,
How I do nmap -sV -T3 ip in this api?

Thx

Invalid JSON format output

HI, I am new to python coding and tried using this module. This works great and only issue I have is when I am trying to feed the JSON output , I get as invalid JSON format.

I ran the attached code and got the output which when validated got attached error. Please let me know if I am missing anything.
output.txt

Error: Parse error on line 1:
{ '192.168.0.104': {
--^
Expecting 'STRING', '}', got 'undefined'

Stealh scan vs firewall detection

Hi,

In this part of the code you use both same option for two different functions. For Stealth Scan I suggest you use : -T[0:1:2] or -sZ for sctp (Stream Control Transmission Protocol) cookie echo, otherwise combine any option with -n and -Pn.

def nmap_stealth_scan(self, host, arg="-sA", args=None):
       """
       nmap -oX - nmmapper.com -sA
       """
...

def nmap_detect_firewall(self, host, arg="-sA", args=None): # requires root
       """
       nmap -oX - nmmapper.com -sA
       @ TODO
       """

how can i pass multiple args

Hi,
I am trying to run multiple args but seems not gettings all args ,shown below
nmap.nmap_version_detection("192.168.1.10",args="-O -p- --script=freevulnsearch.nse")

Please advice
Thanks

Scanning for Custom Set of Ports Does not seem to work

I am running

CentOS Stream release 8
Python 3.9.7
python-nmap 0.7.1

I am trying to ONLY scan a custom set of TCP PORTS for a specific IP Address

My Arguments are: -sV -A -O -p x, y, z, a, b, c

My command to launch the scan in Python is:

result = nmap.nmap_tcp_scan(D.D.D.D, args=arg_list)
The output in the results Stats section for the the command is:

 'stats': {'args': '/usr/bin/nmap -oX - -sT -sV -A -O -p x, D.D.D.D  '
                                                          'y, z, a, b, c'

where D.D.D.D is the IP Address and a,b,c,x,y,z are TCP Port Numbers

The command being populated in NMAP Results dictionary does not look right as the l, I am unsure if the scan is actually being perform on the correct IP and and List of TCP Ports

Any suggestions on how to troubleshoot/verify?

Forgot filter_subdomains?

I'm trying to get the snippet below to run. Looks like filter_subdomains is indeed not declared anywhere!

Python 3.7.6 (default, Dec 30 2019, 19:38:26)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import nmap3
>>> nmap = nmap3.Nmap()
>>> nmap.nmap_dns_brute_script("google.ch")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/user/Library/Python/3.7/lib/python/site-packages/nmap3/nmap3.py", line 115, in nmap_dns_brute_script
    subdomains = self.filter_subdomains(xml_root)
AttributeError: 'Nmap' object has no attribute 'filter_subdomains'

xml output error xml.etree.ElementTree.ParseError: syntax error: line 1, column 0

Hi,
I have installed python3-nmap today and when I am running the scan_command with param -oX (or -oA) it does create the xml and insert the result correctly but it also returns the below error:

  File "/usr/local/lib/python3.8/dist-packages/nmap3/nmap3.py", line 261, in get_xml_et
    return ET.fromstring(command_output)
  File "/usr/lib/python3.8/xml/etree/ElementTree.py", line 1320, in XML
    parser.feed(text)
xml.etree.ElementTree.ParseError: syntax error: line 1, column 0

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "nmapscript.py", line 25, in <module>
    res = nmap.scan_command(target, '-p 22','-oA scan')
  File "/usr/local/lib/python3.8/dist-packages/nmap3/nmap3.py", line 102, in scan_command
    xml_root = self.get_xml_et(output)
  File "/usr/local/lib/python3.8/dist-packages/nmap3/nmap3.py", line 262, in get_xml_et
    except xml.etree.ElementTree.ParseError:
NameError: name 'xml' is not defined

I am calling the param as follow:

import nmap3

nmap = nmap3.Nmap()
target = "192.168.226.130"
res = nmap.scan_command(target, '-p 22','-oA scan')

As looking at the output of one of the scan the command executed is

# Nmap 7.91 scan initiated Mon Nov 30 22:16:36 2020 as: /usr/bin/nmap -oX - -p 22 -oA scan 192.168.226.130

Not sure if the repetition of the -o might be causing the problem, though running it manually doesn't return any error.
Am I doing something not supported/correct?

Thanks

Multi-thread

Hello here,

I'm using your library and I was hopping I could use multithreading to speed up parallel scans.
I already have a list of hosts that are up and I'm passing them into the scan as:

nmap = nmap3.Nmap()
for host in my_list:
  nmap.nmap_version_detection(target=host)

I've been trying to add some parallelism with async or Parallel from joblib without success

Possible to get raw XML output

I was wondering if it is possible to get the raw XML output instead of JSON.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE nmaprun>
<?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?>
<!-- Nmap 7.70 scan initiated Sun Jun 21 12:46:46 2020 as: nmap -oX - -p 80 -Pn 172.17.0.2 -->
<nmaprun scanner="nmap" args="nmap -oX - -p 80 -Pn 172.17.0.2" start="1592743606" startstr="Sun Jun 21 12:46:46 2020" version="7.70" xmloutputversion="1.04">
<scaninfo type="syn" protocol="tcp" numservices="1" services="80"/>
<verbose level="0"/>
<debugging level="0"/>
<host starttime="1592743606" endtime="1592743606"><status state="up" reason="user-set" reason_ttl="0"/>
<address addr="172.17.0.2" addrtype="ipv4"/>
<hostnames>
<hostname name="d118fe00e28c" type="PTR"/>
</hostnames>
<ports><port protocol="tcp" portid="80"><state state="closed" reason="reset" reason_ttl="64"/><service name="http" method="table" conf="3"/></port>
</ports>
<times srtt="59" rttvar="5000" to="100000"/>
</host>
<runstats><finished time="1592743607" timestr="Sun Jun 21 12:46:47 2020" elapsed="0.33" summary="Nmap done at Sun Jun 21 12:46:47 2020; 1 IP address (1 host up) scanned in 0.33 seconds" exit="success"/><hosts up="1" down="0" total="1"/>
</runstats>
</nmaprun>

nmap_version_detection with specific port number

How do I run the nmap_version_detection for a specific port? In my case, it's 80 and I am only willing to get a server banner. The documentation has the following header:

nmap_version_detection(self, target, arg='-sV', args=None)

However, I am not able to test it for a specific port.

Ping scan doesn't return mac address

Hello,

When i execute the function nmap.nmap_ping_scan('192.168.1.0/24'), all hosts (50) have a "None" value as their mac address.
If i run the command /usr/bin/nmap -oX - -sP 192.168.1.0/24, i get the same results, no mac address.
But if i run this same command in sudo, i get the mac address.

Is there a parameter to run this command in sudo ?

Thanks you

still recognice issue with os.geteuid() in Windows 10 21H1

We still identify the issue that your python3-nmap is using "os.geteuid()" which is not exist in Windows 10 (21H1) anymore:

File "C:\Users\mrene\Documents\PYTHON\ncurses-IPventur.py", line 389, in scannen
results = nmap.nmap_os_detection(f'{ip}')
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\utils.py", line 74, in wrapper
if(os.geteuid() == 0):
AttributeError: module 'os' has no attribute 'geteuid'

Therefore actual you cannot do these scans under Windows 10:

nmap_detect_firewall
nmap_os_detection
nmap_stealth_scan
nmap.nmap_os_detection

In our python3-nmap front ncurses-IPventur we use this workaround with win32api.GetConsoleTitle(). Or do you have another solution instead of os.getuid? python-nmap3 version is: 1.4.9

os_version = platform.system()
if os_version == "Windows":
ScreenDel = "cls"
import win32api
check = win32api.GetConsoleTitle()
cmd = "where" if platform.system() == "Windows" else "which"
if "Administrator" in check:
User = "Administrator"
return os_version, User, ScreenDel, cmd
else:
User = "Normal User - limited scan"
return os_version, User, ScreenDel, cmd
else:
ScreenDel = "clear"
cmd = "where" if platform.system() == "Windows" else "which"
if os.geteuid()==0:
User = "Root User"
return os_version, User, ScreenDel, cmd
else:
User = "Normal User - limited scan"
return os_version, User, ScreenDel, cmd

parsing xml results

Hi, question regarding parsing the response. I noticed the response for a call such as nmap.nmap_ping_scan("10.0.0.0/24") will not return a list of responses , it only returns the first host found.

The response gets passed to https://github.com/wangoloj/python3-nmap/blob/32c35be8b7db3fa5a464a723439c02bd95662897/nmap3/nmapparser.py#L112 and the code does xml_root.find("host") which returns the first host in the response. Is this the intended behaviour?

I would imagine this should rather iterate through xml_root.findall("host") and return a list responses.

Add support for individual arguments being sudo instead of needing the whole script be sudo

Is there a way of having only one scan be run as root?
I want to avoid running my whole script as root as it also doing other things (such as storing data in json files) that I want to do a s a standard user.

I've looked at the code and the documentation but I haven't found any ways of having the module prompt the user for superuser access for a specific command.

json output for 'macaddress': None breaks json beautification.

json output for 'macaddress': None breaks json beautification.
Error I recieved:

Parse error on line 1:
...: [], "macaddress": None, "state": {"sta
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

nmap_os_detection not working on Windows 10 20H2

Dear nmap3 creator,

first of all I have to say thank you for your python3 nmap3 module. I've created a little nmap frontend with this nmap3 module:
https://github.com/MrEnergy64/IPventur-Python-Curses

when I start my program under Linux, most scan technics are working fine, when I did it under Window 10 with scan-technic:
nmap_os_detection, I get this error:

Traceback (most recent call last):
File "C:\Users\mrene\Documents\Python\IPventur-Python-1.0v3.py", line 222, in
results = nmap.nmap_os_detection(f'{ip}')
File "C:\Users\mrene\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\utils.py", line 74, in wrapper
if(os.geteuid() == 0):
AttributeError: module 'os' has no attribute 'geteuid'

I know that geteuid is not exist on Windows 10, therefore I used a little trick to identify if someone startet the program in an administrator window or not:

if os_version == "Windows":
import win32api
check = win32api.GetConsoleTitle()
if "Administrator" in check:
User = "Administrator"
else:
User = "Normal User"

so, maybe this could be a solution for you as well. Or is my issue complete different?

Thanks,

Norman

NameError: name 'xml' is not defined

I installed python3-nmap from a pip package and then tried to run the code below.

import nmap3
nmap = nmap3.Nmap()
os_results = nmap.nmap_os_detection("<ipaddress>")

It resulted in the following error:

---------------------------------------------------------------------------
ParseError                                Traceback (most recent call last)
~/anaconda3/envs/python3/lib/python3.6/site-packages/nmap3/nmap3.py in get_xml_et(self, command_output)
    260             self.raw_ouput = command_output
--> 261             return ET.fromstring(command_output)
    262         except xml.etree.ElementTree.ParseError:

~/anaconda3/envs/python3/lib/python3.6/xml/etree/ElementTree.py in XML(text, parser)
   1314     parser.feed(text)
-> 1315     return parser.close()
   1316 

ParseError: no element found: line 1, column 0

During handling of the above exception, another exception occurred:

NameError                                 Traceback (most recent call last)
<ipython-input-2-872ca1c3312a> in <module>
      1 import nmap3
      2 nmap = nmap3.Nmap()
----> 3 os_results = nmap.nmap_os_detection("36.2.24.132")

~/anaconda3/envs/python3/lib/python3.6/site-packages/nmap3/nmap3.py in nmap_os_detection(self, target, arg, args)
    204         """
    205 
--> 206         xml_root = self.scan_command(target=target, arg=arg, args=args)
    207 
    208         os_identified = self.parser.os_identifier_parser(xml_root)

~/anaconda3/envs/python3/lib/python3.6/site-packages/nmap3/nmap3.py in scan_command(self, target, arg, args)
    100 
    101         output = self.run_command(scan_shlex)
--> 102         xml_root = self.get_xml_et(output)
    103 
    104         return xml_root

~/anaconda3/envs/python3/lib/python3.6/site-packages/nmap3/nmap3.py in get_xml_et(self, command_output)
    260             self.raw_ouput = command_output
    261             return ET.fromstring(command_output)
--> 262         except xml.etree.ElementTree.ParseError:
    263             raise NmapXMLParserError()
    264 

NameError: name 'xml' is not defined

Any ideas?

ModuleNotFoundError: No module named 'nmapparser'

It started breaking with the latest CI/CD changes in the version 1.5.3

...
  File "/usr/local/lib/python3.8/site-packages/nmap3/__init__.py", line 22, in <module>
    from .nmap3 import *  # noqa
  File "/usr/local/lib/python3.8/site-packages/nmap3/nmap3.py", line 32, in <module>
    from nmapparser import NmapCommandParser
ModuleNotFoundError: No module named 'nmapparser'

Port Scan

Is there a way that you can scan all 65535 ports using python3-nmap or am I just missing the right function to do so?

Locate nmap on windows

Hey guys,

When using python3-nmap in a Windows 10 environment (nmap is within env variables), getting an error when the get_nmap_path() method is ran. From a quick look its because its only trying "which nmap" which is a unix command.

Is Windows compatibility planned?

Thanks.

udp scan under Windows 10 issue

We identified an issue when we did with Administrator rights an udp scan:
results = nmapscan.nmap_udp_scan(f'{ip}')

under Windows 10 ver. 21H1

File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 78, in default_command
return self.default_command_privileged()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 89, in default_command_privileged
return self.default_command()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 78, in default_command
return self.default_command_privileged()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 89, in default_command_privileged
return self.default_command()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 78, in default_command
return self.default_command_privileged()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 89, in default_command_privileged
return self.default_command()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 78, in default_command
return self.default_command_privileged()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 89, in default_command_privileged
return self.default_command()
File "C:\Users\mrene\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nmap3\nmap3.py", line 78, in default_command
return self.default_command_privileged()
RecursionError: maximum recursion depth exceeded

it works fine with root and normal rights under Linux.

Also tcp scan is running well:
results = nmapscan.nmap_tcp_scan(f'{ip}')

on Windows 10 and Linux

created a new ncurses front-end for your python3-nmap:

https://github.com/MrEnergy64/ncurses-IPventur

python-nmap3 version is: 1.4.9

Recursion limit hit on SYN scan / stack overflow

I decided to run one of the demos in the README, changing the local IP to scanme.nmap.org:

import nmap3
   nmap = nmap3.NmapScanTechniques()
   result = nmap.nmap_syn_scan("scanme.nmap.org")

This resulted in Python hitting the recursion limit, calling two functions repeatedly:

Traceback (most recent call last):
  File "C:\Users\Username\Desktop\doc.py", line 3, in <module>
    result = nmap.nmap_syn_scan("scanme.nmap.org")
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 356, in nmap_syn_scan
    xml_root = self.scan_command(self.sync_scan, target=target, args=args)
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 322, in scan_command
    scan_type_command = self.default_command() + scan
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 78, in default_command
    return self.default_command_privileged()
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 89, in default_command_privileged
    return self.default_command()
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 78, in default_command
    return self.default_command_privileged()
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 89, in default_command_privileged
    return self.default_command()
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 78, in default_command
    return self.default_command_privileged()
  File "C:\Users\Username\AppData\Local\Programs\Python\Python39\lib\site-packages\nmap3\nmap3.py", line 89, in default_command_privileged
    return self.default_command()

RecursionError: maximum recursion depth exceeded

Increasing Python's recursion limit results in a termination of the Python interpreter. I'm running 64-bit Windows 10 with Python 3.9.5, and the interpreter is running with administrative privileges.

Version detection not running with Python3.10

Hi,

I am trying to run version detection and vulners script on Python 3.10 but its failing for some reason

import nmap3

nmap = nmap3.Nmap()
result = nmap.nmap_version_detection('8.8.8.8',args="--script vulners --script-args mincvss+5.0" )
print(result)

and the error looks something like

Traceback (most recent call last):
  File "/home/cybersoldier/Documents/nmap.py", line 4, in <module>
    result = nmap.nmap_version_detection('8.8.8.8',args="--script vulners --script-args mincvss+5.0" ) #Add the -p- flag here, removed for testing purposes
  File "/usr/local/lib/python3.10/dist-packages/nmap3/nmap3.py", line 195, in nmap_version_detection
    xml_root = self.scan_command(target=target, arg=arg, args=args, timeout=timeout)
  File "/usr/local/lib/python3.10/dist-packages/nmap3/nmap3.py", line 125, in scan_command
    output = self.run_command(scan_shlex, timeout=timeout)
  File "/usr/local/lib/python3.10/dist-packages/nmap3/nmap3.py", line 264, in run_command
    raise NmapExecutionError('Error during command: "' + ' '.join(cmd) + '"\n\n' + errs.decode('utf8'))
nmap3.exceptions.NmapExecutionError: Error during command: "/usr/bin/nmap -oX - 8.8.8.8 -sV --script vulners --script-args mincvss+5.0"

I have tried running the script both with and without sudo but the error stays the same.

Results Formatting

I am seeing a formatting error for JSON due to the use of single quote instead of double quote.

test scenario using Google 8.8.8.8 so you can possibly replicate the issue. I have done this on my own IP addresses, but I wanted to keep that info private as you can likely understand.

Editor: Pycharm CE

import nmap3
import pprint

pp = pprint.PrettyPrinter(indent=4)
nmap = nmap3.Nmap()

services = nmap.nmap_version_detection("8.8.8.8")
pp.pprint(services)

results are below. I am having various issues parsing the information so that I can write to a database, json file, conver to yaml etc..

It seems to be related to these errors that PyCharm is showing me

"JSON standard allows only double quoted string as property key:1"

For the results that i have below, my editor shows 138 errors.

{   '8.8.8.8': {   'hostname': [{'name': 'dns.google', 'type': 'PTR'}],
                   'macaddress': None,
                   'osmatch': {},
                   'ports': [   {   'portid': '53',
                                    'protocol': 'tcp',
                                    'reason': 'syn-ack',
                                    'reason_ttl': '0',
                                    'scripts': [],
                                    'service': {   'conf': '8',
                                                   'method': 'probed',
                                                   'name': 'tcpwrapped'},
                                    'state': 'open'},
                                {   'portid': '443',
                                    'protocol': 'tcp',
                                    'reason': 'syn-ack',
                                    'reason_ttl': '0',
                                    'scripts': [],
                                    'service': {   'conf': '10',
                                                   'method': 'probed',
                                                   'name': 'https',
                                                   'product': 'HTTP server '
                                                              '(unknown)',
                                                   'servicefp': 'SF-Port443-TCP:V=7.92%T=SSL%I=7%D=9/10%Time=613BB98E%P=x86_64-apple-darwin17.7.0%r(GetRequest,2C9,"HTTP/1\\.0\\x20302\\x20Found\\r\\nAccess-Control-Allow-Origin:\\x20\\*\\r\\nX-Content-Type-Options:\\x20nosniff\\r\\nLocation:\\x20https://dns\\.google/\\r\\nDate:\\x20Fri,\\x2010\\x20Sep\\x202021\\x2020:01:18\\x20GMT\\r\\nContent-Type:\\x20text/html;\\x20charset=UTF-8\\r\\nServer:\\x20HTTP\\x20server\\x20\\(unknown\\)\\r\\nContent-Length:\\x20216\\r\\nX-XSS-Protection:\\x200\\r\\nX-Frame-Options:\\x20SAMEORIGIN\\r\\nAlt-Svc:\\x20h3=\\":443\\";\\x20ma=2592000,h3-29=\\":443\\";\\x20ma=2592000,h3-T051=\\":443\\";\\x20ma=2592000,h3-Q050=\\":443\\";\\x20ma=2592000,h3-Q046=\\":443\\";\\x20ma=2592000,h3-Q043=\\":443\\";\\x20ma=2592000,quic=\\":443\\";\\x20ma=2592000;\\x20v=\\"46,43\\"\\r\\n\\r\\n<HTML><HEAD><meta\\x20http-equiv=\\"content-type\\"\\x20content=\\"text/html;charset=utf-8\\">\\n<TITLE>302\\x20Moved</TITLE></HEAD><BODY>\\n<H1>302\\x20Moved</H1>\\nThe\\x20document\\x20has\\x20moved\\n<A\\x20HREF=\\"https://dns\\.google/\\">here</A>\\.\\r\\n</BODY></HTML>\\r\\n")%r(HTTPOptions,2A9,"HTTP/1\\.0\\x20302\\x20Found\\r\\nX-Content-Type-Options:\\x20nosniff\\r\\nLocation:\\x20https://dns\\.google/\\r\\nDate:\\x20Fri,\\x2010\\x20Sep\\x202021\\x2020:01:18\\x20GMT\\r\\nContent-Type:\\x20text/html;\\x20charset=UTF-8\\r\\nServer:\\x20HTTP\\x20server\\x20\\(unknown\\)\\r\\nContent-Length:\\x20216\\r\\nX-XSS-Protection:\\x200\\r\\nX-Frame-Options:\\x20SAMEORIGIN\\r\\nAlt-Svc:\\x20h3=\\":443\\";\\x20ma=2592000,h3-29=\\":443\\";\\x20ma=2592000,h3-T051=\\":443\\";\\x20ma=2592000,h3-Q050=\\":443\\";\\x20ma=2592000,h3-Q046=\\":443\\";\\x20ma=2592000,h3-Q043=\\":443\\";\\x20ma=2592000,quic=\\":443\\";\\x20ma=2592000;\\x20v=\\"46,43\\"\\r\\n\\r\\n<HTML><HEAD><meta\\x20http-equiv=\\"content-type\\"\\x20content=\\"text/html;charset=utf-8\\">\\n<TITLE>302\\x20Moved</TITLE></HEAD><BODY>\\n<H1>302\\x20Moved</H1>\\nThe\\x20document\\x20has\\x20moved\\n<A\\x20HREF=\\"https://dns\\.google/\\">here</A>\\.\\r\\n</BODY></HTML>\\r\\n")%r(FourOhFourRequest,307,"HTTP/1\\.0\\x20302\\x20Found\\r\\nAccess-Control-Allow-Origin:\\x20\\*\\r\\nX-Content-Type-Options:\\x20nosniff\\r\\nLocation:\\x20https://dns\\.google/nice%20ports%2C/Trinity\\.txt\\.bak\\r\\nDate:\\x20Fri,\\x2010\\x20Sep\\x202021\\x2020:01:18\\x20GMT\\r\\nContent-Type:\\x20text/html;\\x20charset=UTF-8\\r\\nServer:\\x20HTTP\\x20server\\x20\\(unknown\\)\\r\\nContent-Length:\\x20247\\r\\nX-XSS-Protection:\\x200\\r\\nX-Frame-Options:\\x20SAMEORIGIN\\r\\nAlt-Svc:\\x20h3=\\":443\\";\\x20ma=2592000,h3-29=\\":443\\";\\x20ma=2592000,h3-T051=\\":443\\";\\x20ma=2592000,h3-Q050=\\":443\\";\\x20ma=2592000,h3-Q046=\\":443\\";\\x20ma=2592000,h3-Q043=\\":443\\";\\x20ma=2592000,quic=\\":443\\";\\x20ma=2592000;\\x20v=\\"46,43\\"\\r\\n\\r\\n<HTML><HEAD><meta\\x20http-equiv=\\"content-type\\"\\x20content=\\"text/html;charset=utf-8\\">\\n<TITLE>302\\x20Moved</TITLE></HEAD><BODY>\\n<H1>302\\x20Moved</H1>\\nThe\\x20document\\x20has\\x20moved\\n<A\\x20HREF=\\"https://dns\\.google/nice%20ports%2C/Trinity\\.txt\\.bak\\">here</A>\\.\\r\\n</BODY></HTML>\\r\\n");',
                                                   'tunnel': 'ssl'},
                                    'state': 'open'}],
                   'state': {   'reason': 'syn-ack',
                                'reason_ttl': '0',
                                'state': 'up'}},
    'runtime': {   'elapsed': '70.81',
                   'exit': 'success',
                   'summary': 'Nmap done at Fri Sep 10 15:02:11 2021; 1 IP '
                              'address (1 host up) scanned in 70.81 seconds',
                   'time': '1631304131',
                   'timestr': 'Fri Sep 10 15:02:11 2021'},
    'stats': {   'args': '/usr/local/bin/nmap -oX - -sV 8.8.8.8',
                 'scanner': 'nmap',
                 'start': '1631304060',
                 'startstr': 'Fri Sep 10 15:01:00 2021',
                 'version': '7.92',
                 'xmloutputversion': '1.05'}}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.