Simple port scanner with Python

If you like Python and NMap … there is a very good wrapper from Alexandre Norman! This tutorial show a very simple example for usage.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import nmap

def port_scan(target, ports):
    Simple NMap port scanner example

    @param target: host for scan
    @type target: string
    @param ports: ports for scan
    @type ports: string

    nmap_scan = nmap.PortScanner()
    nmap_scan.scan(str(target), str(ports))

    for host in nmap_scan.all_hosts():
        print '=' * 80
        print 'Host:\t%s' % host
        print 'State:\t%s\n' % nmap_scan[host].state()

        for protocol in nmap_scan[host].all_protocols():
            print 'Protocol(s): %s' % protocol

            port_list = list(nmap_scan[host][protocol].keys())

            for port in port_list:
                print '\n[+] Port: %s' % port
                print '[+] State: %s' % nmap_scan[host][protocol][port]

if __name__ == '__main__':
    port_scan('', '1-1000')

For running see following lines:

# change execution
$ chmod u+x

# start script
$ python -B ./