Author Topic: finished port scanner in python  (Read 3318 times)

0 Members and 6 Guests are viewing this topic.

Offline m1kesanders

  • Serf
  • *
  • Posts: 48
  • Cookies: -5
  • I'm sarcastic, somewhat new, and a grey hat
    • View Profile
finished port scanner in python
« on: March 30, 2013, 11:27:57 am »
ok well I successfully finished the port scanner with the help of RBA and thought I'd paste the code if anyone wanted to see it or needs a port scanner

Code: (python) [Select]

from socket import *
tgtHost=raw_input("What is the web address?: ")
tgtPorts=raw_input("What are the ports seperated by commas? or would you like to test all?: ")
if tgtPorts=="yes" or "ya" or "sure" or "ok" or "k" or "okay" or "kay":
    tgtPorts=21, 22, 23, 25, 42, 43, 53, 67, 79, 80, 102, 110, 115, 119, 123, 135, 137, 143, 161, 179, 379, 389, 443, 445, 465, 636, 993, 995, 1026, 1080, 1090, 1433, 1434, 1521, 1677, 1701, 1720, 1723, 1900, 2409, 3101, 3306, 3389, 3390, 3535, 4321, 4664, 5190, 5500, 5631, 5632, 5900, 7070, 7100, 8000, 8080, 8799, 8880, 9100, 19430, 39720
    def connScan(tgtHost, tgtPort):
        try:
            connSkt=socket(AF_INET, SOCK_STREAM)
            connSkt.settimeout(10)
            connSkt.connect((tgtHost, tgtPort))
            connSkt.settimeout(None)
            print("%d/tcp open"%tgtPort)
            connSkt.close()
        except:
            print("%d/tcp closed"%tgtPort)
    def portScan(tgtHost, tgtports):
        try:
            tgtIP=gethostbyname(tgtHost)
        except:
            print(" Cannot resolve '%s': Unknown host"%tgtHost)
            return
        try:
            tgtName=gethostbyaddr(tgtIP)
            print('\n Scan results for: %s' %tgtName)
        except:
            print('\n Scan results for: %s' %tgtIP)
        for port in tgtPorts:
           print('Scanning port %s'%port)
           connScan(tgtHost, int(port))
    def main():
        portScan(tgtHost, tgtPorts)
    main()
else:
    def connScan(tgtHost, tgtPort):
        try:
            connSkt=socket(AF_INET, SOCK_STREAM)
            connSkt.settimeout(10)
            connSkt.connect((tgtHost, tgtPort))
            connSkt.settimeout(None)
            print("%d/tcp open"%tgtPort)
            connSkt.close()
        except:
            print("%d/tcp closed"%tgtPort)
    def portScan(tgtHost, tgtports):
        try:
            tgtIP=gethostbyname(tgtHost)
        except:
            print(" Cannot resolve '%s': Unknown host"%tgtHost)
            return
        try:
            tgtName=gethostbyaddr(tgtIP)
            print('\n Scan results for: %s' %tgtName)
        except:
            print('\n Scan results for: %s' %tgtIP)
        global tgtPorts
        tgtPorts=tgtPorts.split(',')
        for port in tgtPorts:
            print('Scanning port %s'%port)
            connScan(tgtHost, int(port))
    def main():
        portScan(tgtHost, tgtPorts)
    main()

« Last Edit: March 30, 2013, 04:37:05 pm by m1kesanders »

Offline RedBullAddicted

  • Moderator
  • Sir
  • *
  • Posts: 519
  • Cookies: 189
    • View Profile
Re: Making port scanner in python
« Reply #1 on: March 30, 2013, 12:36:14 pm »
Hi m1kesanders,

I am not quite sure how do you want to get the arguments needed for your program? You have both in your code. First you question for the arguments with raw_input and later you want them to be supplied as commandline args. I used the raw_input method, removed the optparse-parts, fixed the socket timeout (http://stackoverflow.com/questions/3432102/python-socket-connection-timeout) and added the string.split() functions to create a list from the port string. Now it is working. You should always take one step at the time.

Code: (python) [Select]
#!/usr/bin/env python
from socket import *

tgtHost=raw_input("what is the webaddress?: ")
tgtPorts=raw_input("What are the ports seperated by commas?: ")

def connScan(tgtHost, tgtPort):
    try:
        connSkt=socket(AF_INET, SOCK_STREAM)
        connSkt.settimeout(10)   
        connSkt.connect((tgtHost, tgtPort))
        connSkt.settimeout(None)
        print('%d/tcp open' %tgtPort)       
        connSkt.close()
    except:
        print('[-]%d/tcp closed' %tgtPort)

def portScan(tgtHost, tgtPorts):
    try:
        tgtIP=gethostbyname(tgtHost)
    except:
        print("[-] Cannot resolve '%s': Unknown host" %tgtHost)
        return
    try:
        tgtName=gethostbyaddr(tgtIP)
        print('\n Scan results for: %s' %tgtName[0])   
    except:
        print('\n Scan results for: %s' %tgtIP)   
    tgtPorts = tgtPorts.split(',')
    for port in tgtPorts:
        print('Scanning port %s' %port)
        connScan(tgtHost, int(port))

def main():
    portScan(tgtHost, tgtPorts)

if __name__=='__main__':
    main()

Code: [Select]
redbull@evilos ~ $ sudo python portscan.py
what is the webaddress?: www.google.de
What are the ports seperated by commas?: 80,22

Scan results for: bk-in-f94.1e100.net
Scanning port 80
80/tcp open
Scanning port 22
[-]22/tcp closed[/closed]

Just wanted to fix some errors and not recode your portscanner. There still is a lot to optimize and some unneeded stuff. You maybe want to have a look into scapy or twisted for this project?

Cheers,
RBA
« Last Edit: March 30, 2013, 12:37:04 pm by RedBullAddicted »
Deep into that darkness peering, long I stood there, wondering, fearing, doubting, dreaming dreams no mortal ever dared to dream before. - Edgar Allan Poe

Offline m1kesanders

  • Serf
  • *
  • Posts: 48
  • Cookies: -5
  • I'm sarcastic, somewhat new, and a grey hat
    • View Profile
Re: Making port scanner in python
« Reply #2 on: March 30, 2013, 12:44:45 pm »
Ok thank you soooo much I've been on this for now about 13 hours lol you just saved me a lot more hassle

Offline RedBullAddicted

  • Moderator
  • Sir
  • *
  • Posts: 519
  • Cookies: 189
    • View Profile
Re: Making port scanner in python
« Reply #3 on: March 30, 2013, 01:03:01 pm »
no problem :) If you go on working on it please keep us updated and if you have problems again feel free to post them here. Btw. If you want to get the arguments supplied via command line you can use sys.argv (example: http://stackoverflow.com/questions/983201/python-and-sys-argv). You can use if statements and regex to validate the input and so on. As mentioned before there is a lot of things you can do to optimize the script.

Cheers,
RBA
Deep into that darkness peering, long I stood there, wondering, fearing, doubting, dreaming dreams no mortal ever dared to dream before. - Edgar Allan Poe

Offline m1kesanders

  • Serf
  • *
  • Posts: 48
  • Cookies: -5
  • I'm sarcastic, somewhat new, and a grey hat
    • View Profile
Re: Making port scanner in python
« Reply #4 on: March 30, 2013, 01:26:29 pm »
alright thanks again and will do when I get a fully optimized working one i'll post the code in case someone wants to take a look at it

Offline RedBullAddicted

  • Moderator
  • Sir
  • *
  • Posts: 519
  • Cookies: 189
    • View Profile
Re: finished port scanner in python
« Reply #5 on: March 30, 2013, 05:06:30 pm »
Hi,

nice to see that you went on working on it :) As you are new to python or scripting/programming in general I would like to give you one advice. You repeated a lot of your code and whenever that happens you should ask yourself if it is really necessary. In most cases you can just make a function with the repeating code and use this one when ever you need it. In your example its just the place where you put your if statement.

Code: (python) [Select]
#!/usr/bin/env python
from socket import *

tgtHost=raw_input("what is the webaddress?: ")
tgtPorts=raw_input("What are the ports seperated by commas? or would you like to test all?: [yes]")

def connScan(tgtHost, tgtPort):
    try:
        connSkt=socket(AF_INET, SOCK_STREAM)
        connSkt.settimeout(10)   
        connSkt.connect((tgtHost, tgtPort))
        connSkt.settimeout(None)
        print('%d/tcp open' %tgtPort)       
        connSkt.close()
    except:
        print('[-]%d/tcp closed' %tgtPort)
        connSkt.close()

def portScan(tgtHost, tgtPorts):
    if tgtPorts == "yes" or "ya" or "sure" or "ok" or "k" or "okay" or "kay":
        tgtPorts= "21, 22, 23, 25, 42, 43, 53, 67, 79, 80, 102, 110, 115, 119, 123, 135, 137, 143, 161, 179, 379, 389, 443, 445, 465, 636, 993, 995, 1026, 1080, 1090, 1433, 1434, 1521, 1677, 1701, 1720, 1723, 1900, 2409, 3101, 3306, 3389, 3390, 3535, 4321, 4664, 5190, 5500, 5631, 5632, 5900, 7070, 7100, 8000, 8080, 8799, 8880, 9100, 19430, 39720"   

    try:
        tgtIP=gethostbyname(tgtHost)
    except:
        print("[-] Cannot resolve '%s': Unknown host" %tgtHost)
        return
    try:
        tgtName=gethostbyaddr(tgtIP)
        print('\n Scan results for: %s' %tgtName[0])   
    except:
        print('\n Scan results for: %s' %tgtIP)   
    tgtPorts = tgtPorts.split(',')
    for port in tgtPorts:
        print('Scanning port %s' %port)
        connScan(tgtHost, int(port))

def main():
    portScan(tgtHost, tgtPorts)

if __name__=='__main__':
    main()

Its exact the same code just with the if statement placed in a function. Its still not a perfect script and I would like to recommend that you go over it again. Maybe tomorrow when you have a bit more distance to it. I know it gets harder and harder the longer you sit in front of a script. Btw. just realized that the socket was not closed in the except statement. I fixed that aswell. You see that placing the if statement to another position your code could be reduced from 62 to 42 lines. I am still not sure why you did a gethostbyname and later a gethostbyaddr. I think this is not necessary as the user already provided the hostname.

Cheers,
RBA
Deep into that darkness peering, long I stood there, wondering, fearing, doubting, dreaming dreams no mortal ever dared to dream before. - Edgar Allan Poe

Offline m1kesanders

  • Serf
  • *
  • Posts: 48
  • Cookies: -5
  • I'm sarcastic, somewhat new, and a grey hat
    • View Profile
Re: finished port scanner in python
« Reply #6 on: March 30, 2013, 06:36:00 pm »
Ok I see what you're saying, hey I've actually been curious what does __name__="__main__" mean?
well implemented the shorter way and added like two extra lines for another little feature I was doing lol it went from a 68 line script to a 35 line haha thanks
« Last Edit: March 30, 2013, 06:45:48 pm by m1kesanders »

Offline proxx

  • Avatarception
  • Global Moderator
  • Titan
  • *
  • Posts: 2803
  • Cookies: 256
  • ФФФ
    • View Profile
Re: finished port scanner in python
« Reply #7 on: March 30, 2013, 07:46:30 pm »
Hi,

nice to see that you went on working on it :) As you are new to python or scripting/programming in general I would like to give you one advice. You repeated a lot of your code and whenever that happens you should ask yourself if it is really necessary. In most cases you can just make a function with the repeating code and use this one when ever you need it. In your example its just the place where you put your if statement.

Code: (python) [Select]
#!/usr/bin/env python
from socket import *

tgtHost=raw_input("what is the webaddress?: ")
tgtPorts=raw_input("What are the ports seperated by commas? or would you like to test all?: [yes]")

def connScan(tgtHost, tgtPort):
    try:
        connSkt=socket(AF_INET, SOCK_STREAM)
        connSkt.settimeout(10)   
        connSkt.connect((tgtHost, tgtPort))
        connSkt.settimeout(None)
        print('%d/tcp open' %tgtPort)       
        connSkt.close()
    except:
        print('[-]%d/tcp closed' %tgtPort)
        connSkt.close()

def portScan(tgtHost, tgtPorts):
    if tgtPorts == "yes" or "ya" or "sure" or "ok" or "k" or "okay" or "kay":
        tgtPorts= "21, 22, 23, 25, 42, 43, 53, 67, 79, 80, 102, 110, 115, 119, 123, 135, 137, 143, 161, 179, 379, 389, 443, 445, 465, 636, 993, 995, 1026, 1080, 1090, 1433, 1434, 1521, 1677, 1701, 1720, 1723, 1900, 2409, 3101, 3306, 3389, 3390, 3535, 4321, 4664, 5190, 5500, 5631, 5632, 5900, 7070, 7100, 8000, 8080, 8799, 8880, 9100, 19430, 39720"   

    try:
        tgtIP=gethostbyname(tgtHost)
    except:
        print("[-] Cannot resolve '%s': Unknown host" %tgtHost)
        return
    try:
        tgtName=gethostbyaddr(tgtIP)
        print('\n Scan results for: %s' %tgtName[0])   
    except:
        print('\n Scan results for: %s' %tgtIP)   
    tgtPorts = tgtPorts.split(',')
    for port in tgtPorts:
        print('Scanning port %s' %port)
        connScan(tgtHost, int(port))

def main():
    portScan(tgtHost, tgtPorts)

if __name__=='__main__':
    main()

Its exact the same code just with the if statement placed in a function. Its still not a perfect script and I would like to recommend that you go over it again. Maybe tomorrow when you have a bit more distance to it. I know it gets harder and harder the longer you sit in front of a script. Btw. just realized that the socket was not closed in the except statement. I fixed that aswell. You see that placing the if statement to another position your code could be reduced from 62 to 42 lines. I am still not sure why you did a gethostbyname and later a gethostbyaddr. I think this is not necessary as the user already provided the hostname.

Cheers,
RBA

Just wanted to mention that for a port scanner it might be desired behaviour not to close the connection.,
It means more traffic, more packets etc.
Its more polite to do so though.
Wtf where you thinking with that signature? - Phage.
This was another little experiment *evillaughter - Proxx.
Evilception... - Phage

Offline RedBullAddicted

  • Moderator
  • Sir
  • *
  • Posts: 519
  • Cookies: 189
    • View Profile
Re: finished port scanner in python
« Reply #8 on: March 30, 2013, 08:11:59 pm »
Just wanted to mention that for a port scanner it might be desired behaviour not to close the connection.,
It means more traffic, more packets etc.
Its more polite to do so though.

True :) And I guess it would be faster to create the socket, send all packets and close it instead of creating the socket over and over again for every single connect. Thats one of the points I wanted him to find out by himself. Next to this there are a lot of other things that could use some optimization. This is why I tried to motivate him to post his progress. Only thing I did was correcting some faults that were obvious without touching the logic of the script to much. In my opinion you have the best learning experience when you find the "mistakes" on your own.

Quote from: RBA
Its still not a perfect script and I would like to recommend that you go over it again

and sorry m1kesanders for talking about you as if you were not here. I know this sucks but we are only trying to help a fellow python coder with his first steps. Don't know if I would have ever been able to learn python without the help of techb during my fist contact with this awesome scripting language. Yes techb :) I still <3 you for being a awesome person :)
Deep into that darkness peering, long I stood there, wondering, fearing, doubting, dreaming dreams no mortal ever dared to dream before. - Edgar Allan Poe

Offline m1kesanders

  • Serf
  • *
  • Posts: 48
  • Cookies: -5
  • I'm sarcastic, somewhat new, and a grey hat
    • View Profile
Re: finished port scanner in python
« Reply #9 on: March 30, 2013, 08:32:44 pm »
and sorry m1kesanders for talking about you as if you were not here. I know this sucks but we are only trying to help a fellow python coder with his first steps. Don't know if I would have ever been able to learn python without the help of techb during my fist contact with this awesome scripting language. Yes techb :) I still <3 you for being a awesome person :)

Sucks? this is awesome every time I find the mistake or error and fix it it feels great thanks  ;D

Offline 3vilp4wn

  • Serf
  • *
  • Posts: 46
  • Cookies: 11
  • :D
    • View Profile
    • Evil Ninja Hackers
Re: finished port scanner in python
« Reply #10 on: May 03, 2013, 07:51:37 am »
I'm working on a port scanner in python as well, but it's not as good as yours yet :(
One thing you could look into though is using argparse to eliminate the need for user input once it's running.
With argparse, you can just type something like "portscan.py www.google.com --ports 80 21 21" or "portscan.py www.google.com --ports all"
Makes it way nicer to use on the terminal.

I might use this code in my port scanner, would that be ok with you? (with credit of course.)

Also, did this start from the port scanner in Violent Python?  The variable names and structure look similar.
Shooting is not  too good for my enemies.

Offline m1kesanders

  • Serf
  • *
  • Posts: 48
  • Cookies: -5
  • I'm sarcastic, somewhat new, and a grey hat
    • View Profile
Re: finished port scanner in python
« Reply #11 on: May 04, 2013, 11:27:58 pm »
I'm working on a port scanner in python as well, but it's not as good as yours yet :(
One thing you could look into though is using argparse to eliminate the need for user input once it's running.
With argparse, you can just type something like "portscan.py www.google.com --ports 80 21 21" or "portscan.py www.google.com --ports all"
Makes it way nicer to use on the terminal.

I might use this code in my port scanner, would that be ok with you? (with credit of course.)

Also, did this start from the port scanner in Violent Python?  The variable names and structure look similar.



Ya you can use the code I have no problem with it, that's why I posted it here : )


and no this port scanner I started from scratch I had no templates or books helping me along