def show_help(self): if self.autoclean:self.clean() LAYOUT =" {!s:16} {!s:10}" write("\n#gScanopy Commands\n#w================\n\n") write(" Command Description\n #g-------#w #g-----------\n") for com,des in self.commands.items(): print(LAYOUT.format(*[com,des]))
def startThreads(self): if config['verbose']:write("#g[#w~#g]#w Scanning ...\n") else: global an an = anym("Scanning[{}]".format(config['target'])) an.start() for _ in range(config["threads"]): thread = scanThread() thread.start() self.THREADS.append(thread) for t in self.THREADS:t.join() self.finFlag = True
def run(self): while True: lock.acquire() if config['ports'].empty(): lock.release() break port = config['ports'].get() lock.release() sock = self.createSocket() if config['protocol']=="tcp":result = PortScan(sock, config['target'], port, config['timeout']).tcpScan else:result = PortScan(sock, config['target'], port, config['timeout']).udpScan if result: config['result']['open'].append(port) if config['verbose']:write("#g[#w+#g] {}#w:#g{}#w{}/#g{}#w :#g OPEN\n".format(config['target'], port,getService(port), config['protocol'])) if config['servScan']: if config['verbose']:write("[~] Scanning for [{}] Service Info...\n".format(port)) info =config['servScan'].scan(config['target'], port, config['protocol']) if info: config['result']['vscan'][port]=parser(info) config['result']['open'].remove(port) else: config['result']['close']+=1 if config['verbose']:write("#y[#r-#y] {}#w:#r{}#y{}#y/#r{}#y :#r CLOSED\n".format(config['target'], port, getService(port, status="close"), config['protocol'])) if isKilled():break config['ports'].task_done() config['ret']+=1
def quit(self,sig,fream): if not self.cmdCtrlC: if not config['verbose']: an.done = True if config['servScan']:config['servScan'].done = True kill() write("\n#y[#r~#y]#r Aborting#y...\n") while config['ret'] != config['threads']: continue if config['verbose'] and self.printed <2: for t in self.THREADS:write("#y[#r!#y] Thread-{} :#y Aborted #r!\n".format(t.ident)) write("\n#r[#y!#r]#y Scan Die#r:#y reason#r:#y Aborted by user #r!!!\n\n") if not self.printed:self.printPorts() self.abroFlag = True else:sys.exit("\n")
def show_options(self): if self.autoclean:self.clean() LAYOUT =" {!s:15} {!s:10} {!s:50} {!s:39}" self.tarOpt = odict([("target",['yes',"Specify Target hostname or IP",self.target]), ("ports",['optional',"Specify Ports To Scan",self.ports]), ("protocol",['optional', "Specify Connection Protocol",self.protocol]), ("timeout", ['optional',"Specify Connection Timeout",self.timeout])]) self.modOpt = odict([ ("threads", ['optional', "Specify Number Of Threads",self.threads]), ("vscan", ['optional', "Specify 'true' To Enable Service And Version Scan",self.vscan]), ("verbose",['optional',"Specify 'true' To Show Output",self.verbose])]) write("\n#gTarget Options\n#w==============#g\n\n") print(LAYOUT.format("[option]","[RQ]","[Description]","[value]")) write("#w -------- ---- ------------- -------\n") for opt in self.tarOpt.keys(): val = self.tarOpt[opt] if opt == "ports":val[-1]="top-200-ports" print(LAYOUT.format(*[opt]+val)) write("\n#wModule Options\n#g==============#w\n\n") print(LAYOUT.format("[option]","[RQ]","[Description]","[value]")) write("#g -------- ---- ------------- -------\n") for opt in self.modOpt.keys(): print(LAYOUT.format(*[opt]+self.modOpt[opt]))
def run(self): self.done = False anim = ('[= ]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[ =]', '[ =]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[= ]') i = 0 dot = "." while not self.done: if len(dot) ==4: dot = "." write("\b\b\b\b") write(" ") write("\r"+anim[i % len(anim)]+self.prompt+dot) se(1.0/5) i+=1 dot+="." if self.done:break
def start(self): global event,kill,isKilled,lock event = threading.Event() kill = lambda :event.set() isKilled =lambda :event.isSet() lock = threading.Lock() self.THREADS = [] self.finFlag = False self.abroFlag = False self.printed = 0 target = self.target ports = self.ports protocol = self.protocol.lower() timeout = self.timeout versionScan = self.vscan threads = self.threads verbose = self.verbose if not target.strip(): errmsg("Target is not selected") return False ports = getPorts(ports) if not ports: errmsg("Invalid Ports Selected") return False try:timeout = float(timeout) except ValueError: if not timeout.strip() or not timeout.isdigit(): errmsg("timeout must be an number") return False timeout = int(timeout) if not timeout: errmsg("timeout cannot be '{}'".format(timeout)) return False if not threads.strip() or not threads.isdigit(): errmsg("threads Must be an number") return False threads = int(threads) if not threads: errmsg("threads cannot be '{}'".format(threads)) return False if not verbose.strip() or verbose.lower() not in {'true','false'}: errmsg("verbose: must be 'true' or 'false'") return False if not versionScan.strip() or versionScan.lower() not in {'true', 'false'}: errmsg("versionScan: must be 'true' or 'false'") return False verbose = True if verbose.lower() == "true" else False versionScan = True if versionScan.lower() == "true" else False if versionScan: if not self.runner: write("[~] Loading ....\n") servScan = serviceScan() servScan.verbose = verbose self.runner = servScan else:servScan = self.runner else:servScan = False if threads > len(ports):threads = len(ports) qus = qu() for port in ports:qus.put(port) global config config = {"target":target, "ports":qus, "protocol":protocol, "timeout":timeout, "threads":threads, "servScan": servScan, "verbose": verbose, "ret":0, "result":{ "open":[], "close":0, "vscan": {}}} if verbose: write("#w[#y~#w]#y Starting #g{}#y Threads#w....\n".format(threads)) mainThread = threading.Thread(target=self.startThreads) mainThread.daemon = True mainThread.start() while not self.finFlag: if self.abroFlag:break if self.abroFlag:return if not verbose: an.done = True else: for thread in self.THREADS:write("#g[#w*#g]#w Thread-{} : has #gFinshied\n".format(thread.ident)) self.printed+=1 write("\n") self.printPorts() self.printed+=1 mainThread.join() return
def shell(self): signal.signal(signal.SIGINT, self.quit) signal.signal(signal.SIGTERM,self.quit) try: while True: cmd = str(input("Scanopy> ")) if not cmd:continue elif cmd.lower() == "update": write("[~] Checking for updates...\n") if not self.checkInternet():errmsg("Error: Unable to update reason: no internet connection") else: conn = httplib.HTTPSConnection("raw.githubusercontent.com") conn.request("GET", "/Oseid/scanopy/master/core/version.txt") repoVersion = conn.getresponse().read().strip().decode() with open("core"+sep+"version.txt") as ver: thisVersion = ver.read().strip() if repoVersion == thisVersion: write(" [*] The tool is up to date!\n") else: ask = input(" [?] An update has been found, do you want to update now?(Y:n)> ").strip() while not ask: ask = input(" [!] please Answer with 'y' for yes or 'n' for no ?> ").strip() if ask.lower() in ("yes","y"): write("\n[~] Updating...please wait\n") script = urllib.urlopen("https://raw.githubusercontent.com/Oseid/scanopy/master/scanopy.py").read() with open("scanopy.py", "wb") as scanopy: scanopy.write(script) with open("core"+sep+"version.txt", "w") as ver: ver.write(repoVersion) write(" [+] Successfully updated :)\n\n[*] Please relaunch tool to apply updates :)\n") break else:write("\n[*] Ok Maybe later :)\n") elif cmd.lower() == "exit": print("[*] Exit Scanopy script...bye :)") break elif cmd.lower() == "autoclean": self.autoclean = True if not self.autoclean else False write("[+] autoclean ==> {}\n".format("#w[#gON#w]" if self.autoclean else "#y[#rOFF#y]")) elif cmd.lower() in ("cls", "clear"):self.clean() elif cmd.lower() == "help":self.show_help() elif cmd.lower() == "options":self.show_options() elif cmd.lower() == "start": self.cmdCtrlC = False self.start() self.cmdCtrlC = True elif cmd.lower().startswith("set"): data = "".join(cmd.strip().split("set")).strip() if not data:write("Usage: set <Option> <Value>\n") elif not " " in data: opt = data.strip() if not opt in self.options:write("[!] Unknown Option: '{}' !!!\n".format(opt)) elif opt == "target":write("Usage: set target <target hostname or ip> e.g: set target google.com\n") elif opt == "ports":write("Usage: set ports <port1,port2,port-range> e.g: set ports 20-25,80,445,8080,200-1025\n") elif opt == "protocol":write("Usage: set protocol <protocol(tcp,udp)> e.g: set protocol udp\n") elif opt == "timeout":write("Usage: set timeout e.g: set timeout 0.05\n") elif opt == "threads":write("Usage: set threads <number_of_threads> e.g: set threads 200\n") elif opt == "vscan":write("Usage: set vscan <true, false> e.g: set vscan true") elif opt == "verbose":write("Usage: set verbose <true, false> e.g: set verbose true") elif data.count(" ") != 1:write("[!] Unknown Command: '{}' !!!\n".format(data)) else: opt,val = data.split(" ") opt = opt.lower() if opt not in self.options: write("[!] Unknown Option: '{}' !!!\n".format(opt)) continue for option in self.options: if opt == option: if option == "ports":self.portsSet = True if option == "protocol": if not val.lower() in ("tcp", "udp"): errmsg("Invalid Connection Protocol Must be 'tcp' or 'udp'") break if not self.portsSet:self.ports = self.portsByProto[val.lower()] write("[+] {} ==> {}\n".format(option, val)) exec('self.{} = "{}"'.format(option,val)) break elif cmd.lower().startswith("exec"): execom = "".join(cmd.split("exec")[1]).strip() if not execom: write("[!] exec <command <args>: eg: ls -alt>\n") continue system(execom) elif cmd.lower() in self.options:write("[*] {} = {} ".format(cmd, eval("self.{}".format(cmd.lower())))) elif cmd.lower().startswith("reset"): opt = cmd.lower().strip().split(" ") if len(opt) == 2: opt = opt[1].lower() if opt == "all": write("[~] Reset All Options...\n") for option in self.options: defval = self.defaultVal[option] if option != "ports" else self.resetPorts() exec('self.{} = "{}"'.format(option, defval)) write(" [+] {} ==> {}\n".format(option, defval if option != "ports" else "top-200-ports")) continue if opt not in self.options: write("[!] Unable to reset option : reason: Unknown option !!!\n") continue defaultValue = self.defaultVal[opt] if opt != "ports" else self.resetPorts() exec('self.{} = "{}"'.format(opt,defaultValue)) write("[~] {} ==> {}\n".format(opt, defaultValue if opt != "ports" else "top-200-ports")) continue write("[*] Usage: reset <option, all> (e.g: reset target)") else:write("[!] Unknown Command: '{}' !!!\n".format(cmd)) print(" ") sys.exit(1) except EOFError:pass
def printPorts(self): vv = False if config['servScan'] and config['result']['vscan']: vv = True write("[*] Services Info OF[{}]\n".format(config['target'])) for port,info in config['result']['vscan'].items(): space ="==========="+"="*len(str(port))+"=====" write(space+"\n[*] PORT["+str(port)+"] INFO:\n"+space+ "\n") for key,val in info: if not len(val):continue write(" [+] {} : {}\n".format(key.strip(), val.strip())) write("\n") write("\n") if not config['verbose'] and config['result']['close']:write("[*] Not Shown: [{}] closed ports.\n\n".format(config['result']['close'])) if config['result']['open']: write("PORT\t STATE\t SERVICE\n") for port in config['result']['open']:write("{}/{}\t {}\t {}\n".format(port,config['protocol'],"OPEN",getService(port, raw=True)))
sys.exit(1) if not path.isfile("core"+sep+"version.txt"): print("[!] Error: File[{}] Is Missing Please reinstall the tool to reinstall it!!!".format("core"+sep+"version.txt")) sys.exit(1) if sys.version_info.major <=2: import Queue,httplib,urllib qu = lambda : Queue.Queue() input = raw_input else: import queue,http.client as httplib, urllib.request as urllib qu = lambda : queue.Queue() input = input from core.services import Services from core.vslib import write,parser,serviceScan errmsg = lambda msg: write("#y[#r-#y] Error: {}#r !!!#w\n".format(msg)) class anym(threading.Thread): def __init__(self,prompt): threading.Thread.__init__(self) self.prompt = prompt self.done = False def run(self): self.done = False anim = ('[= ]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[ =]', '[ =]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[ = ]', '[= ]') i = 0 dot = "."