Author Topic: [PYTHON] A simple port scanner (whith some questions)  (Read 1512 times)

0 Members and 1 Guest are viewing this topic.

Offline christian25r

  • NULL
  • Posts: 4
  • Cookies: 2
    • View Profile
[PYTHON] A simple port scanner (whith some questions)
« on: June 20, 2015, 11:05:21 pm »
hello,

i'm new to python programming and here is a fisrt code i've done

so,here is a port scanner i've done , it works fine on localhost ,
but when i try to scan a website , after waiting 10 minutes there is nothing
what is wrong with my code.



Code: [Select]
from socket import *

print "Simple port scanner"
print "-------------------"
print ""
adress = raw_input("Enter adress (or localhost): ")
ip = gethostbyname(adress)
print adress,"has the IP:",ip
alpha = int(raw_input("Port (min):"))
omega = int(raw_input("Port (max):"))
   

def scanner(ip,min_port, max_port):
    count = 0
    for ports in range(alpha, omega):
        s = socket(AF_INET, SOCK_STREAM)
        result = s.connect_ex((ip, ports))
        if(result == 0) :
            print 'Port %d: is OPEN' % (ports,)
            count = count + 1
        s.close()
    print "Scanning finshed !"
    print ""
    print "Found",count,"open ports"           
       
       
 
   
print ""
print "Beggin to scan..."
scanner(ip,alpha,omega)

   

Here is the output for localhost:

Code: [Select]
Simple port scanner
-------------------

Enter adress (or localhost): localhost
localhost has the IP: 127.0.0.1
Port (min):0
Port (max):100

Beggin to scan...
Port XX: is OPEN
Port XX: is OPEN
Scanning finshed !

Found 2 open ports


and the output for google (for example)
and there is the problem , there is NOTHING :(

Code: [Select]
Simple port scanner
-------------------

Enter adress (or localhost): google.com
google.com has the IP: 74.125.195.100
Port (min):24
Port (max):82

Beggin to scan...


Thank you for helping me .
« Last Edit: June 21, 2015, 12:18:51 am by christian25r »

Offline kenjoe41

  • Symphorophiliac Programmer
  • Administrator
  • Baron
  • *
  • Posts: 990
  • Cookies: 224
    • View Profile
Re: [PYTHON] A simple port scanner (whith some questions)
« Reply #1 on: June 21, 2015, 01:09:42 pm »
Ignoring the typos with a assumption that english aint your first language.

In your scanner() function, you needed 'min_port' and 'max_port' arguments though you end up using alpha and omega variables. Then you pass alpha and omega when you call the scanner() function.

We also talked about creating a different socket for the same client but for a different port, you sure you can't use the same socket to connect to the different ports?

You have alot of errors to look up for so it would be better to connect in a try...except clause to look out for any connection problems and to also catch the OverflowError for when you are given a port out of range. Wait, connect_ex returns mostly an error not an exception though the OverflowError is still thrown so still look out for those.

Don't know what else but they are alot of results on Google about port scanners in python so read up and make this code better.
If you can't explain it to a 6 year old, you don't understand it yourself.
http://upload.alpha.evilzone.org/index.php?page=img&img=GwkGGneGR7Pl222zVGmNTjerkhkYNGtBuiYXkpyNv4ScOAWQu0-Y8[<NgGw/hsq]>EvbQrOrousk[/img]

Offline christian25r

  • NULL
  • Posts: 4
  • Cookies: 2
    • View Profile
Re: [PYTHON] A simple port scanner (whith some questions)
« Reply #2 on: June 21, 2015, 01:17:25 pm »
yes i'm not native English speaking , i come from France ^^
thank you for you anwser Kenjoe41.
just have take few other source-codes to improve my script.
ex: (http://stackoverflow.com/questions/16045946/modified-violent-python-port-scanner-prints-but-doesnt-run)
and:(http://www.pythonforpentesting.com/2013/10/port-scanning-with-python.html)
wil try to add try/exceot and banner grabbing , and also the time taken to do all the processes.
and open all my ebooks and websites to find more informations .
i have also done my introduction in the member introduction section





« Last Edit: June 21, 2015, 01:18:36 pm by christian25r »

Offline christian25r

  • NULL
  • Posts: 4
  • Cookies: 2
    • View Profile
Re: [PYTHON] A simple port scanner (whith some questions)
« Reply #3 on: June 26, 2015, 02:04:15 pm »
back ^^

hello,

i have done some changes (have add try/except and add two settimeouts) and have test it on a friend's website , and it seems to work .

Here is the code:


Code: [Select]
from socket import *

print "Simple port scanner"
print "-------------------"
print ""
address = raw_input("Enter address (or localhost): ")
ip = gethostbyname(address)
print address,"has the IP:",ip
alpha = int(raw_input("Port (min):"))
omega = int(raw_input("Port (max):"))
   

def scanner(ip,alpha, omega):
    count = 0   
    for ports in range(alpha, omega):
        try:
            print "Scanning port :%d" % (ports,)
            s = socket(AF_INET, SOCK_STREAM)
            s.settimeout(3)
            s.connect((ip, ports))
            s.settimeout(3)
            print "Port %d: is OPEN" % (ports,)
            count = count + 1
        except:
            print "Port %d is CLOSED" % (ports,)
        s.close()
    print "Scanning finished !"
    print ""
    print "Found %d open ports" % (count)         
       
       
 
   
print ""
print "Begin to scan..."
scanner(ip,alpha,omega)

And the output is:

Code: [Select]
Simple port scanner
-------------------

Enter address (or localhost): xxx.xxx.org
xxx.xxx.org has the IP: xx.xx.xxx.xxx
Port (min):79
Port (max):82

Begin to scan...
Scanning port :79
Port 79 is CLOSED
Scanning port :80
Port 80: is OPEN
Scanning port :81
Port 81 is CLOSED
Scanning finshed !

Found 1 open ports
>>> ================================ RESTART ================================
>>>
Simple port scanner
-------------------

Enter address (or localhost): xxx.xxx.org
xxx.xxx.org has the IP: xx.xx.xxx.xxx
Port (min):440
Port (max):445

Begin to scan...
Scanning port :440
Port 440 is CLOSED
Scanning port :441
Port 441 is CLOSED
Scanning port :442
Port 442 is CLOSED
Scanning port :443
Port 443: is OPEN
Scanning port :444
Port 444 is CLOSED
Scanning finished !

Found 1 open ports
>>>

Now im trying to improve with threads (but same.... never used it ^^)
not sure if it's understandable , but i try
ex: if i want to scan 100 ports , i want to divide it , and scan 10 with thread 1 , 10 with tread 2, etc .....

Have a nice day
« Last Edit: June 26, 2015, 02:13:51 pm by christian25r »

Offline khofo

  • EZ's Swashbuckler
  • Knight
  • **
  • Posts: 350
  • Cookies: 25
  • My humor is so black, it could go cotton picking.
    • View Profile
Re: [PYTHON] A simple port scanner (whith some questions)
« Reply #4 on: June 30, 2015, 11:20:19 am »
I know, that OP, might be leeching the forum.
but here is how I reorganized and cleaned a bit his code :p
and I guess I'll be adding a way to have the choice to save the output to .txt file


Code: (python) [Select]
#!/usr/bin/python
#Created by: Christian25r
#Simple port scanner


#Imports
from socket import *
import re


######################
#Top
print "/////////////Simple port scanner////////////////"
print "                                                "
print "/////////////by: Christian25r///////////////////"
print "------------------------------------------------"
print "                                                "


#get user input and verify


while True:
        address = raw_input("Please Enter Target IPv4 Address (or localhost):")
        if re.match('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$',address):
                break
        print "ERROR:Invalid IPv4 Address Format try again"     #This is regex (regular expressions), it's a cooler way to try the IP,
                                                                #since mistakes in the format can be made, and a traceback is not cool




ip = gethostbyname(address)
print address,"has the IP:",ip
while True:
        try:
                min_port = int(raw_input("Port (min):"))
                max_port = int(raw_input("Port (max):"))       #added try to also verify the ports
                break
        except:
                print "Invalid ports"




############################


#Functions


def scanner(ip,min_port, max_port):
        count = 0   
        for ports in range(min_port, max_port):
                try:
                        print "Scanning port :%d" % (ports,)
                        s = socket(AF_INET, SOCK_STREAM)
                        s.settimeout(3)
                        s.connect((ip, ports))
                        s.settimeout(3)
                        print "Port %d: is OPEN" % (ports,)
                        count = count + 1
                except:
                        print "Port %d is CLOSED" % (ports,)
                        s.close()
       
        print "Done scanning !"
        print ""
        print "Found %d open ports" % (count)         
           
###########################       


#Executions


print "----------------------------------------------------"
print "Proceeding to scan..."
scanner(ip, min_port, max_port)


#End


print "----------------------------------------------------"
print "----------------------Done--------------------------"
raw_input("---------------Press 'Enter' to exit----------------")
print "Goodbye!"
« Last Edit: June 30, 2015, 11:27:26 am by Khofo »
Quote from: #Evilzone
<Spacecow18> priests are bad ppl
<Insanity> Holy crap
Of course God isnt dead. He's out there partying with the Easter Bunny, Santa Clause, Tooth Fairy, and the Man on the moon...
Some of my work: Introduction to Physical Security

Offline christian25r

  • NULL
  • Posts: 4
  • Cookies: 2
    • View Profile
Re: [PYTHON] A simple port scanner (whith some questions)
« Reply #5 on: July 21, 2015, 11:53:35 am »
hello,

here is a new source i have done for my port-scanner (always free for use in legal way for white-hats)



Code: [Select]

from socket import *


open_p, closed_p = [], []
reponse = ["OPEN PORTS","CLOSED PORTS","SCANNING PORTS:","TYPE","SCANNING","ADDRESS"]

address = raw_input ("{}: ".format(reponse[5]))
ip = gethostbyname(address)

print "{0}:{1}\n".format(reponse[4],ip)



def scan_c(address,port): 
    s = socket(AF_INET,SOCK_STREAM)
    s.settimeout(0.17)
    result = s.connect_ex((address,port))   
    if result == 0:
        open_p.append(port)
        s.shutdown(2)
    else:
        closed_p.append(port)   
    s.close


def main():
    print reponse[2]
    for port in range (0,101):
        print port,
        scan_c(address,port)

   
if __name__ == "__main__":
    main()


print "\n\n{}".format(reponse[0])
for elements in open_p:
    print "{0} {1} :{2}".format(elements,reponse[3],getservbyport(elements))


this range system was only for test , will change it next to add a user input range system ,and a port list system too
now i want to do multithreading and queue on it (but no clue how to do it , i'm still noob in python !! ), and next add all options i had on one of the first versions (whois,bannergrabing,nslookup,etc..  only in python )
if someone have an idea how to thread and queue this new source ^^

Have a nice day all :)
« Last Edit: July 21, 2015, 12:20:45 pm by christian25r »