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


def ping(host, port):
        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,, 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 ( == None):
        host = str(

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

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

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

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

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


if __name__ == "__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: -t -t -p 21,80 -n 2

See you.

Python port scanner

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s