python-3.xprivilegesnmap

Python3.4 -Nmap Requires root privileges


Running on Mac Os 10.10.5 Running this script to scan for hosts on the network:

import nmap
nm = nmap.PortScanner()
nm.scan('192.168.5.1/24', arguments='-O')
for h in nm.all_hosts():
    if 'mac' in nm[h]['addresses']:
        print(nm[h]['addresses'], nm[h]['vendor'])

When running it its printing:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 290, in analyse_nmap_xml_scan
    dom = ET.fromstring(self._nmap_last_output)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/xml/etree/ElementTree.py", line 1326, in XML
    return parser.close()
  File "<string>", line None
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 "/Users/*/Documents/*.py", line 3, in <module>
    nm.scan('192.168.0.0/24', arguments='-O')
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 235, in scan
    nmap_err_keep_trace = nmap_err_keep_trace)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/nmap/nmap.py", line 293, in analyse_nmap_xml_scan
    raise PortScannerError(nmap_err)
nmap.nmap.PortScannerError: 'TCP/IP fingerprinting (for OS scan) requires root privileges.\nQUITTING!\n'

I tried going to that directory and running this command in the terminal: sudo python *.py

({'mac': '02:62:31:41:6D:84', 'ipv4': '192.168.5.1'}, {})

Any suggestions to run the script from the python IDLE?


Solution

  • Running IDLE as root might work, but it might not be a great idea. sudo idle

    Option 1 (recommended):

    Put the code requiring elevated privileges in a python file which you run with sudo. I assume you want to play with the results, so you could have the script save the results to a file, which you then read in IDLE.

    The following code works in python 2.7 and 3.4

    import nmap
    import json
    
    nm = nmap.PortScanner()
    nm.scan('192.168.5.1/24',arguments='-O') #Note that I tested with -sP to save time
    output = []
    with open('output.txt', 'a') as outfile:
      for h in nm.all_hosts():
        if 'mac' in nm[h]['addresses']:
          item = nm[h]['addresses']
          if nm[h]['vendor'].values():
            item['vendor'] = list(nm[h]['vendor'].values())[0]
          output.append(item)
      json.dump(output, outfile)
    

    Run sudo python nmaproot.py Since the file is written by root, you need to change ownership back to yourself. sudo chown -r myusername output.txt

    In IDLE:

    import json
    input = open('output.txt','r'):
    json_data = json.load(input)
    json_data[0] # first host
    

    Option 2 (not recommended at all):

    Use subprocess to run the file with the elevated code as root and return the output. It gets kind of messy and requires you to hardcode your password...but it's possible.

    from subprocess import Popen, PIPE
    cmd = ['sudo', '-S', 'python', 'nmaproot.py']
    sudopass = 'mypassword'
    p = Popen(cmd, stdin=PIPE, stderr=PIPE,universal_newlines=True, stdout=PIPE)
    output = p.communicate(sudopass + '\n')
    

    I'm unsure of how you can run a given portion of your python code as root without saving it to a file and running it separately. I recommend you go with option 1 as option 2 isn't very good (but it was fun to figure out).