![]() |
|
Building a network port scanner - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Hacking (https://sinister.li/Forum-Hacking) +--- Forum: Hacking Tools (https://sinister.li/Forum-Hacking-Tools) +--- Thread: Building a network port scanner (/Thread-Building-a-network-port-scanner) Pages:
1
2
|
Building a network port scanner - WH0_4M_1 - 04-05-2017 I am new to script writing and I was wondering if anyone has any tips on how i could make a fast port scanner. I have made a basic scanner in python, your feedback would be much appreciated. Code: "#!/usr/bin/env python
from socket import *
import sys, getopt, time, os
#To-DO-LIST
#Version 1.1:
#1: Add more comments to code
#2: Make -l work with -s and -e
#3: Make script run more efficently(THREADS can be used)
#4: Add better error handling
#5: Make code more dry
#NEXT:
#Create Port-Knocking script for better service detection
#Try to get service version
#Basic OS detection
#better OS detection
#OS version detection
#Find dns server for target
#Add premade Port Lists for more efficent scanning(1000 most common ports)
#add -f to display only specified services
#Store Scaned hosts in a file
#Add support for UDP scanning
def Banner():
print("\n"*50)
author = "N30N_PH4NT0M"
version = 1.0
version_stage = "ALPHA"
text = """ _______ _______ _______ _________ _______ ___ _______
( ____ \|\ /|( __ )( ____ \\__ __/ ( ) / ) ( ____ )
| ( \/| ) ( || ( ) || ( \/ ) ( | () () | / /) | | ( )|
| | | (___) || | / || (_____ | | | || || | / (_) (_ | (____)|
| | ____ | ___ || (/ /) |(_____ ) | | | |(_)| |(____ _)| _____)
| | \_ )| ( ) || / | | ) | | | | | | | ) ( | (
| (___) || ) ( || (__) |/\____) | | | | ) ( | | | | )
(_______)|/ \|(_______)\_______) )_(_____|/ \| (_) |/
(_____) """
print("--------------------------------------------------------------------------------")
print(text)
print("Version "+str(version)+" "+version_stage+"\t\t\t\t Created by "+author)
print("--------------------------------------------------------------------------------")
print("")
def Space_Layout(DATA_LIST,STR_LENGTH):
STR_LENGTH = len(str(DATA_LIST[STR_LENGTH]))
LIST_LENGTHS = []
MAX_LENGTH = 0
for i in range (len(DATA_LIST)):
LIST_LENGTHS.append(int(len(str(DATA_LIST[i]))))
MAX_LENGTH = max(LIST_LENGTHS)
SPACES = (" "*(int(MAX_LENGTH)-int(STR_LENGTH)+1))
return SPACES
def User_Error():
print("Syntax invalid")
print("---------------------------------------------------------------------------------------------------------")
print("Usage: GH0ST_SC4NN3R.py -t <targets> -s <start_port> -e <end port> -l <list_of_ports> -v <veribosity level>")
print("---------------------------------------------------------------------------------------------------------")
print("Example: GH0ST_SC4NN3R.py -t 127.0.0.1 -s 80 -e 8080")
print("---------------------------------------------------------------------------------------------------------")
print("Example: GH0ST_SC4NN3R.py -t 127.0.0.1 -l 21,22,80,8080,443")
print("---------------------------------------------------------------------------------------------------------")
print("Example: GH0ST_SC4NN3R.py -t 127.0.0.1,192.168.1.1 -v 3")
print("---------------------------------------------------------------------------------------------------------")
print("Example: GH0ST_SC4NN3R.py -f ips.txt -l ")
print("---------------------------------------------------------------------------------------------------------")
print("Use -h for more info")
print("")
def Command_Help():
print("--------------------------------------------------------------------------------")
print("'-h' Shows this help page")
print("'-t <target_ip>' Specifiy the target you want to scan")
print("'-s <start_port>' Specify the port that the scan starts from")
print("'-e <end_port>' Specify the port that the scan end in")
print("'-v <level>' The veribosity level of the script(1-4)")
print("'-l <list...>' Allows you to specify a list of ports to scan")
print("'-f <file>' Allows you to specify a file to read targets from(line seperated)")
print("--------------------------------------------------------------------------------")
def Read_file(filename):
try:
ips = []
F = open(filename,"r")
for line in F:
ips.append(line.strip())
return ips
except FileNotFoundError:
print("[ERROR] IP file "+str(filename)+" not found")
return []
def main(argv):
skip_host = False
targetIPs = []
serv_name = []
serv_state = []
Target_Selected = 0
Start_Port = 20
End_Port = 1000
Veribosity_Level = 1
Port_List = []
result = ""
ARRAY_COUNTER = 0
SERVICES_PRINTED = 0
HELP_ENABLED = False
dev_silent_on_error = False
try:
opts, args = getopt.getopt(sys.argv[1:],"t:s:e:v:l:f:h")
except getopt.GetoptError:
User_Error()
try:
for opt, arg in opts:
if(opt == "-h"):
HELP_ENABLED = True
elif(opt == "-t"):
PL1 = arg.split(",")
for i in range (len(PL1)):
targetIPs.append(gethostbyname(str(PL1[i])))
elif(opt == "-s"):
Start_Port = int(arg)
elif(opt == "-e"):
End_Port = int(arg)+1
elif(opt == "-v"):
Veribosity_Level = int(arg)
elif(opt == "-l"):
PL = arg.split(",")
for i in range (0,(len(PL))):
Port_List.append(int(PL[i]))
elif(opt == "-f"):
try:
targetIPs = Read_file(arg)
except:
HELP_ENABLED = True
exit(0)
else:
print("'",opt,"'"," is a invalid argument")
except:
raise Exception("Command Argument function failed")
Banner()
if(len(targetIPs) == 1):
print("Starting scan on host "+str(targetIPs[Target_Selected]))
elif(len(targetIPs) >= 1):
hosts = ""
for i in range (len(targetIPs)):
if(i < (len(targetIPs)-1)):
hosts += targetIPs[i]+"-"
else:
hosts += targetIPs[i]
print("Starting scan on hosts "+hosts)
else:
if(HELP_ENABLED == False):
print("No Hosts Found")
else:
Command_Help()
if(Port_List != []):
Start_Port = 0
End_Port = len(Port_List)
for i2 in range(len(targetIPs)):
print("")
try:
if(dev_silent_on_error == False):
print("Services for "+(str(gethostbyaddr(targetIPs[Target_Selected])[0]))+" ["+targetIPs[Target_Selected]+"] ["+str(len(targetIPs)-(i2))+" hosts left]:")
except:
print("[ERROR]: "+targetIPs[i2]+" is unreachable")
skip_host = True
print("----------------------------------------") if SERVICES_PRINTED == 0 else ...
for i in range(Start_Port, End_Port):
if skip_host == False:
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIPs[Target_Selected], (int(Port_List[i])) if Port_List!= [] else i))
if(result == 0):
serv_state.append("OPEN")
elif(result == 10061 or Veribosity_Level <= 2):
serv_state.append("CLOSED")
elif(Veribosity_Level >= 2):
serv_state.append("UNKNOWN")
else:
serv_state.append("ERROR")
try:
if(serv_state[ARRAY_COUNTER] == "OPEN"):
serv_name.append(str(getservbyport(Port_List[i])) if Port_List != [] else str(getservbyport(i)))
else:
serv_name.append("")
except:
serv_name.append("Unknown")
SERVICES_PRINTED+=1
if(Veribosity_Level == 1 and serv_state[ARRAY_COUNTER] != "UNKNOWN" and serv_state[ARRAY_COUNTER] != "CLOSED"):
print((str(Port_List[i])+Space_Layout(Port_List,i)+(str(serv_state[ARRAY_COUNTER]))+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER]) if Port_List != [] else str(i)+" "+str(serv_state[ARRAY_COUNTER])+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER])))
elif(Veribosity_Level == 2 and serv_state[ARRAY_COUNTER] != "UNKNOWN"):
print((str(Port_List[i])+Space_Layout(Port_List,i)+(str(serv_state[ARRAY_COUNTER]))+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER]) if Port_List != [] else str(i)+" "+str(serv_state[ARRAY_COUNTER])+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER])))
elif(Veribosity_Level == 3):
print((str(Port_List[i])+Space_Layout(Port_List,i)+(str(serv_state[ARRAY_COUNTER]))+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER]) if Port_List != [] else str(i)+" "+str(serv_state[ARRAY_COUNTER])+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER])))
elif(Veribosity_Level == 4):
print((str(Port_List[i])+Space_Layout(Port_List,i)+(str(serv_state[ARRAY_COUNTER]))+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER]) if Port_List != [] else str(i)+" "+str(serv_state[ARRAY_COUNTER])+Space_Layout(serv_state,ARRAY_COUNTER)+str(serv_name[ARRAY_COUNTER])))
elif(Veribosity_Level < 1 or Veribosity_Level > 4 ):
raise Exception("Invalid Veribosity level: "+str(Veribosity_Level)+" only levels between 1 and 4 are valid")
os.kill()
else:
SERVICES_PRINTED-=1
s.close()
ARRAY_COUNTER+=1
print("----------------------------------------") if SERVICES_PRINTED != 0 else ...
if(dev_silent_on_error == False and SERVICES_PRINTED == 0):
print("No Open Ports were found")
print("----------------------------------------")
SERVICES_PRINTED=0
Target_Selected+=1
skip_host = False
if __name__ == "__main__":
main(sys.argv[1:])RE: Building a network port scanner - m0dem - 04-06-2017 Please use the code tags! RE: Building a network port scanner - Zorxio - 04-09-2017 ................................................................ RE: Building a network port scanner - WH0_4M_1 - 05-07-2017 (04-09-2017, 11:47 PM)Zorxio Wrote: What's wrong with nmap? https://github.com/nmap/nmap I made it for educational purposes, I have made a variety of basic hacking tools to understand how they work, although I do use nmap for regular use. RE: Building a network port scanner - pvnk - 05-07-2017 (04-09-2017, 11:47 PM)Zorxio Wrote: What's wrong with nmap? https://github.com/nmap/nmap Who said there was anything wrong? RE: Building a network port scanner - Blink - 05-07-2017 Seems nice, you could add more comments, but I see that in your future additions area. You should try remaking it in C. (Faster + Education) RE: Building a network port scanner - pvnk - 05-07-2017 (05-07-2017, 10:59 PM)Ender Wrote: Seems nice, you could add more comments, but I see that in your future additions area.and a little bit of aids RE: Building a network port scanner - insidious - 05-08-2017 (05-07-2017, 10:59 PM)Ender Wrote: Seems nice, you could add more comments, but I see that in your future additions area. I second this. If you're interested in the low-level aspects of networking and plan to at least move in that direction, C is a good next step for sure. Other than that, the code is quite easy to understand, nice job RE: Building a network port scanner - WH0_4M_1 - 05-14-2017 (05-08-2017, 12:38 AM)insidious Wrote:(05-07-2017, 10:59 PM)Ender Wrote: Seems nice, you could add more comments, but I see that in your future additions area. Thanks, Good point, Python is a language which was originally designed for people to learn programming, C is probably more suitable for making hacking tools. RE: Building a network port scanner - mothered - 05-14-2017 (05-07-2017, 10:59 PM)Ender Wrote: Seems nice, you could add more comments Very good point. With every script/source, It's always good practice to add as many comments of relevance as possible. Naturally, keeping It short and straight to the point Is a must. |