Python port scanner

Today, we are going to implement a simple port scanner implemented in python 3. The code is quite simple, and I think that it doesn’t need any explanation.

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

from functools import partial
from multiprocessing import Pool
import socket
import optparse

DEFAULT_CORE_NUMBER = 2


def ping(host, port):
    try:
        socket.socket().connect((host, port))
        return port
    except socket.error as err:
        return False


def scanPorts(host, ports, cores):
    p = Pool(cores)
    ping_host = partial(ping, host)

    return filter(bool, p.map(ping_host, ports))


def main():
    parser = optparse.OptionParser('%prog -t <target host> -p <target port(s)> -n <number of cores>')
    parser.add_option('-t', dest='host', type='string', help='Specify the target host')
    parser.add_option('-p', dest='ports', type='string', help='Specify the target port(s); Separate them by commas.')
    parser.add_option('-n', dest='cores', type='int', help='Specify the number of CPU cores do you want to use.')

    (options, args) = parser.parse_args()

    if (options.host == None):
        print(parser.usage)
        exit(0)
    else:
        host = str(options.host)

    if (options.ports == None):
        ports = range(1, 65536)
    else:
        ports = list(map(int, str(options.ports).split(',')))

    if (options.cores == None):
        cores = DEFAULT_CORE_NUMBER
    else:
        cores = options.cores

    print('\nScanning ports on ' + host + ' ...')

    portsScanned = list(scanPorts(host, ports, cores))

    print(str(len(portsScanned)) + ' ports available.')
    print(portsScanned)

    print('\nDone.')


if __name__ == "__main__":
    main()

The script has three different options:

  • -t: Specify the target host. It is a mandatory option.
  • -p: Specify target ports.
  • -n: Specify the number of cores that are going to be used.

We can see some invocation examples:

scanner.py
scanner.py -t 127.0.0.1
scanner.py -t 127.0.0.1 -p 21,80 -n 2

See you.

Python port scanner