Escaner de puertos con rangos en python


Bueno, aquí os dejo un pequeño escáner de puertos que usa multi-hilos para aumentar la velocidad de respuesta por cada petición.

Este módulo permite escanear rangos de IP’s (X-Y, *) y puertos (A-Z, A,B,C,…Z) y nos informa del tipo de servicio que esta en uso en el caso que el puerto este abierto (ej.: 80 => www).

Código portscan.py

#!/usr/bin/env python
# -*- coding: utf8 -*-
 
import socket, sys, threading, time, os
from thread import error
 
timeout = 2
maxthread = 1024
 
x = 0
err = False
show = True
 
def usage():
    print "Uso: %s IP PORT" % sys.argv[0]
    print "\nIP admite rangos a-z y el port rangos x-y a,b,...z."
    print "Ejemplos:"
    print "\t%s 127.0.0.1 1-1024" % sys.argv[0]
    print "\t%s 192.168.1.2-100 21,22,25,80,115,443" % sys.argv[0]
    print "\t%s 217.127.97.* 21\n" % sys.argv[0]
    if sys.platform == "win32":
        os.system("pause")
    sys.exit()
 
class PortScanner(threading.Thread):
    def __init__(self, host, port, services):
        threading.Thread.__init__(self)
        self.host = host
        self.port = int(port)
        self.services = services
    def run(self):
        global x
        global err
        global show
        if err:
            sys.exit()
        socket.setdefaulttimeout(timeout)
        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as e:
            print e
            err = True
            sys.exit()
        try:
            self.s.connect((self.host, self.port))
            service = "unknown"
            for serv in self.services:
                serv = serv.strip("\n")
                if str(self.port)+"/tcp" in serv.split():
                    service = serv.split()[0]
                    break
            if show:
                print "\nPORT\tSTATUS\tSERVICE"
                show = False
            print "%s\tOPEN\t%s" % (str(self.port), service)
            x += 1
        except:
            pass
        self.s.close()
 
if __name__ == "__main__":
    servs = []
    if sys.platform == "linux2":
        f = open("/etc/services", "r")
    else:
        f = open("c:\WINDOWS\system32\drivers\etc\services", "r")
    servs = f.readlines()
    f.close()
    if len(sys.argv) < 2:
        usage()
    elif len(sys.argv) == 3:
        try:
            host = socket.gethostbyname(sys.argv[1]).split(".")
        except:
            host = sys.argv[1].split(".")
        try:
            a = host[0]; b = host[1]; c = host[2]; d = host[3]
        except:
            print "Error en la resolucion del host"
            sys.exit()
        if host[0] == "*": a = "1-255"
        if host[1] == "*": b = "1-255"
        if host[2] == "*": c = "1-255"
        if host[3] == "*": d = "1-254"
        if a.find("-") == -1: a += "-"+a
        if b.find("-") == -1: b += "-"+b
        if c.find("-") == -1: c += "-"+c
        if d.find("-") == -1: d += "-"+d
        for A in range(int(a.split("-")[0]), int(a.split("-")[1])+1):
            for B in range(int(b.split("-")[0]), int(b.split("-")[1])+1):
                for C in range(int(c.split("-")[0]), int(c.split("-")[1])+1):
                    for D in range(int(d.split("-")[0]), int(d.split("-")[1])+1):
                        ip = str(A)+"."+str(B)+"."+str(C)+"."+str(D)
                        ports = sys.argv[2]
                        if ports.find("-") == -1 and ports.find(",") == -1:
                            ports += "-"+ports
                        x = 0
                        if ports.find("-") > 0:
                            ports = ports.split("-")
                            if not ports[0].isdigit() or not ports[1].isdigit():
                                print "Rango invalido\n"
                                usage()
                                sys.exit()
                            print "Escanenado %s:" % ip
                            for port in range(int(ports[0]), int(ports[1])+1):
                                if err:
                                    sys.exit()
                                while threading.activeCount() >= maxthread:
                                    time.sleep(0.5)
                                scan = PortScanner(ip, port, servs)
                                try:
                                    scan.start()
                                except error as err:
                                    print "\nError: \"%s\"" % err
                            scan.join()
                            if x > 0:
                                print "\n%d puerto(s) abierto(s)\n" % x
                            show = True
                        elif ports.find(",") > 0:
                            ports = ports.split(",")
                            print "Escanenado %s:" % ip
                            for port in ports:
                                if err:
                                    sys.exit()
                                if not port.isdigit():
                                    print "%s no es un digito" % port
                                    sys.exit()
                                while threading.activeCount() >= maxthread:
                                    time.sleep(0.5)
                                scan = PortScanner(ip, port, servs)
                                try:
                                    time.sleep(0.005)
                                    scan.start()
                                except error as err:
                                    print "\nError: \"%s\"" % err
                            scan.join()
                            if x > 0:
                                print "\n%d puerto(s) abierto(s)\n" % x
                            show = True
    else: usage()

Lo primero que necesitamos es el interprete de python. En Linux normalmente ya vendrá, en Windows lo bajamos aquí. En Linux lo hacemos ejecutable para facilitar la ejecución:

chmod +x portscan.py

Y para ejecurarlo:

./portscan.py IP PORT

En Windows una vez que tenemos el interprete de python instalado no es mas que situarnos desde la consola (cmd) en el directorio donde tenemos el programa y escribir:

portscan.py IP PORT

Su uso es fácil, para escanear por ejemplo todos los puertos privilgiados del 1 al 1024 de nuestra IP:

./portscan.py 127.0.0.1 1-1024

En mi caso, la salida del ejemplo anterior sería:

Escanenado 127.0.0.1:
 
PORT     STATUS     SERVICE
21       OPEN       ftp
25       OPEN       smtp
53       OPEN       domain
80       OPEN       www
 
4 puerto(s) abierto(s)

Para escanear los puertos 22 y 80 de nuestra red local, por ejemplo, 192.168.1.X:

./portscan.py 192.168.1.* 22,80

o

./portscan.py 192.168.1.1-254 22,80

Este programa tiene 2 parametros que se pueden modificar que estan en la cabezera del mismo modulo y son timeout y maxthread.

Donde:
timeout: Es el tiempo maximo que debemos esperar antes de dar como cerrado el puerto.
maxthread: Define el maximo numero de hilos (thread) que se pueden lanzar simultaneamente.

Un saludo

QR Code - Take this post Mobile!
Use this unique QR (Quick Response) code with your smart device. The code will save the url of this webpage to the device for mobile sharing and storage.
Dejar un comentario?

12 Comentarios.

  1. Take a separate quote from the company asking for coverage if
    you want insurance coverage to your furniture during transit.

    The services provided by a Moving Company – A moving company
    helps companies and folks to relocate their
    items from a single spot to an additional whether in the identical town or a single town to one more.
    Therefore if you’re moving anywhere in Australia such as
    Melbourne, Sydney, Perth, Brisbane, Adelaide, Canberra, Darwin,
    Townsville and any other state or if you are
    moving to or from Australia, be sure to obtain the services of a decent overseas moving company.

    Feel free to visit my site cloud storage companies stock

  2. Any type of gold chain, ring, or earrings, can give someone a relaxed style, and
    also look very trendy for this season. Not only is Junior sized clothing
    not cut for a woman’s figure, it also shows more skin that we would like.
    It should not be a surprise that if some is more than interested in going for online shopping besides looking forward
    to gain the upper limit benefit by buying unique clothes, then it
    needs less mention that the is the thing that can help you realize the dream of buying clothes.

    my site … boutique dresses wholesale uk

  3. I loved as much as you’ll receive carried out right here.
    The sketch is tasteful, your authored subject matter stylish.
    nonetheless, you command get bought an edginess over that you wish be delivering the following.
    unwell unquestionably come further formerly again as exactly the
    same nearly very often inside case you shield this
    hike.

  4. The biggest reason for including direct mail in your marketing campaign is Google.
    In order to make the campaign profitable, it is usually necessary to mail out to many thousands of people,
    each one a potential customer. Note that the white edge is part of the
    QR code, it is actually black patterns on a white box,
    so make sure you get it all.

  5. Di daerah-daerah yang gak memperbolehkan judi, usaha taruhan on-line akan menjadi lebih berkembang daripada negara lainnya yang memperbolehkan aktivitas taruhan.
    Melihat Dari cara bet judi dan cara cara per judian di internet
    di website Agen, Agen Kami sajikan supaya mempermudah penggemar bola supaya mempelajari & mempergunakan internet digital online bersama cara cara yang tepat.
    ‘ He talked about Poison being the perfect
    example of that advice.

  6. This can be useful for private data transfers with other users, surfing websites anonymously, and of course changing your IP address.

    Also, with the right app installed one should be able to easily find streaming video content.
    Autofocus, image stabilisation and a dual LED flash are all provided to simplify the
    task of taking photos whilst simultaneously improving their quality.

  7. Perhaps, for them the best means of travel would be by air, followed by a BWI taxi service.
    Wedding is a lifetime experience and hence you need to give time to each detail.
    These vehicles provide customers with a novel experience and can inspire
    sales by adding additional target markets to the mix.

  8. Look when it reaches this simple example: Say tend to be 30 yrs old
    and earn a monthly salary of $10,000. It is comparable to the River Seine in Paris, as heading to have a
    specially-treated sand, umbrellas, and humidifiers.

  9. It’s great that you are getting thoughts from this article
    as well as from our dialogue made at this place.

  10. New Balane New Balance 1500 Femme QSKDH La signora McDonald, ha esortato
    il pubblico a rivolgersi allo stato per quanto riguarda
    House Bill 4780, che ha dichiarato che rimangono
    in discussione in Parlamento. Il disegno di legge priverebbe comuni svolgimento
    delle elezioni dei loro diritti, raccogliere le tasse, e di fornire servizi di valutazione.
    New Balance Logo New Balance 1000 FdVvq Quando OP è femmina, questi commenti rafforzano la convinzione che la maggior parte delle persone hanno
    un livello subconscio che le donne dovrebbero essere giudicati sulle loro prestazioni,
    indipendentemente dal contesto. La maggior parte delle persone proposte in risposta al tuo commento rafforzano l’idea che le donne sono particolarmente importanti come potenziali partner sessuali, anche quando
    sono presentati in un contesto professionale. New Balance Ml 574 Newblance
    UmSyu Raccontaci il tuo negozio favoloso e
    quali prodotti o servizi che offrite? Chiunque può acquistare il mio libro, basta provare!
    Un mese per mese resoconto di shopping e stile (Kensington Citadel Press,
    2009). E ‘disponibile presso tutti i negozi Barnes Noble e
    online. New Balance 410 Femme Discount Balance kFNTm Omonimo talk show corrente Fox
    News Channel di Beck ha debuttato 19 gen 2009 a oltre 2,4
    milioni di telespettatori. Questo lancio incredibile costruita sul
    successo di Beck televisivo night show sulla
    CNN Headline News, che ha ospitato il 2006, 2008. New Balance
    M670 New Balance Cuir MhXGT Idee Reader, anche utilizzando sacchi di
    grano per la conservazione scaricato. Un altro di detto vetro repurposes olio d’oliva, come germoglio
    di fiore vaso.

    New Balance Classic Chaussures New Balance Homme kEfjx Settimane e settimane di
    simili metodi squadra gioiello della corona ha vinto il primo posto in hip hop e jazz
    categorie nel concorso 1 marzo spiaggia di Ocean City.
    La squadra ha vinto anche 3000 dollari per essere il più alto
    punteggio di squadra, allenatore Loni Haggin, una Eleanor
    Roosevelt laureato 2000 e ex membro della squadra pom
    se stesso.. New Balance 1300 New Balance 373 Homme RVyzw 14 ° secolo mistico er en Off principali santi
    patroni Italy.The Palazzo Piccolomini costruito nel 1459 dal famoso architetto Bernardo Rossellino,
    apprendistato v Leon Battista Alberti. Palazzo Piccolomini er en tra i siti
    più popolari su Piazza del Campo. new balance classic New Balance 1080 xCtdT Compito autocommiserazione.
    Anche se quello che ho casi in tutto il resoconto elemento fondazione
    fa primre tipi di frode davvero si distingue correttamente inviando messaggi non necessari programmatore sito orWhen non sarò in grado di concettualizzare ad alcuni che
    punisce la semplice realizzazione e bug sinspecific, e l’hotel è rinomato per
    alcuni Hkan In che inturn Together.

  11. Everyone knows that the best online games come out in Korea
    and Japan first. You may find that the 100 zombie miniatures provided may not be enough to last throughout
    an entire game with a larger party, but sets of extra zombies are available
    for purchase. But most of these online games are designed to entertain and so after a while,
    some kids get bored.

  12. Nice post. I was checking continuously this blog and I’m impressed!
    Very useful information particularly the last part :) I care for such
    information much. I was looking for this certain information for a very long
    time. Thank you and good luck.

Deje un comentario


NOTA - Puede usar estosHTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>