python based nmap port scanning

Nmap is a great tool to run scans on remote hosts and networks. python-nmap module uses underline nmap binary to run scans and adds advantage of programmable controls to get desired results. To start install python-nmap module.


pip3 install python-nmap
Collecting python-nmap
  Downloading https://files.pythonhosted.org/packages/dc/f2/9e1a2953d4d824e183ac033e3d223055e40e695fa6db2cb3e94a864eaa84/python-nmap-0.6.1.tar.gz (41kB)
     |████████████████████████████████| 51kB 386kB/s
Installing collected packages: python-nmap
  Running setup.py install for python-nmap ... done
Successfully installed python-nmap-0.6.1

Here is a sample code how to use above module and run scans. Save this as scanit.py


#!/usr/local/bin/python3
import nmap
import sys

host=sys.argv[1]
# Initialize object
hostscan=nmap.PortScanner()
# Run scan on tcp and udp in fast mode
results=hostscan.scan(hosts=host, arguments='-sUT -T5')

# Fetch host state, tcp and udp results
state=hostscan[host].state()
tcpports=hostscan[host].all_tcp()
udpports=hostscan[host].all_udp()

print(state,";",tcpports,";",udpports)

Output


python3 scanit.py 192.168.0.23
up ; [22, 53, 80, 443, 3000, 8086, 8090] ; [53, 68, 514, 5353]