(host=RESTAPI_SERVER_HOST, port=RESTAPI_SERVER_PORT)
REST-JSON API client
REST-JSON API client
REST - JSON API client
def client(host=RESTAPI_SERVER_HOST, port=RESTAPI_SERVER_PORT):
    """
    REST-JSON API client
    """
    addr = "http://%s:%d" % (host, port)
    logger.info("Starting REST-JSON API client to '%s'..." % addr)

    try:
        _client(addr)
    except Exception, ex:
        if not isinstance(ex, urllib2.HTTPError):
            errMsg = "there has been a problem while connecting to the "
            errMsg += "REST-JSON API server at '%s' " % addr
            errMsg += "(%s)" % ex
            logger.critical(errMsg)
            return

    taskid = None
    logger.info("Type 'help' or '?' for list of available commands")

    while True:
        try:
            command = raw_input("api%s> " % (" (%s)" % taskid if taskid else "")).strip().lower()
        except (EOFError, KeyboardInterrupt):
            print
            break

        if command in ("data", "log", "status", "stop", "kill"):
            if not taskid:
                logger.error("No task ID in use")
                continue
            raw = _client("%s/scan/%s/%s" % (addr, taskid, command))
            res = dejsonize(raw)
            if not res["success"]:
                logger.error("Failed to execute command %s" % command)
            dataToStdout("%s\n" % raw)

        elif command.startswith("new"):
            if ' ' not in command:
                logger.error("Program arguments are missing")
                continue

            argv = ["sqlmap.py"] + shlex.split(command)[1:]

            try:
                cmdLineOptions = cmdLineParser(argv).__dict__
            except:
                taskid = None
                continue

            for key in list(cmdLineOptions):
                if cmdLineOptions[key] is None:
                    del cmdLineOptions[key]

            raw = _client("%s/task/new" % addr)
            res = dejsonize(raw)
            if not res["success"]:
                logger.error("Failed to create new task")
                continue
            taskid = res["taskid"]
            logger.info("New task ID is '%s'" % taskid)

            raw = _client("%s/scan/%s/start" % (addr, taskid), cmdLineOptions)
            res = dejsonize(raw)
            if not res["success"]:
                logger.error("Failed to start scan")
                continue
            logger.info("Scanning started")

        elif command.startswith("use"):
            taskid = (command.split()[1] if ' ' in command else "").strip("'\"")
            if not taskid:
                logger.error("Task ID is missing")
                taskid = None
                continue
            elif not re.search(r"\A[0-9a-fA-F]{16}\Z", taskid):
                logger.error("Invalid task ID '%s'" % taskid)
                taskid = None
                continue
            logger.info("Switching to task ID '%s' " % taskid)

        elif command in ("list", "flush"):
            raw = _client("%s/admin/%s/%s" % (addr, taskid or 0, command))
            res = dejsonize(raw)
            if not res["success"]:
                logger.error("Failed to execute command %s" % command)
            elif command == "flush":
                taskid = None
            dataToStdout("%s\n" % raw)

        elif command in ("exit", "bye", "quit", 'q'):
            return

        elif command in ("help", "?"):
            msg =  "help        Show this help message\n"
            msg += "new ARGS    Start a new scan task with provided arguments (e.g. 'new -u \"http://testphp.vulnweb.com/artists.php?artist=1\"')\n"
            msg += "use TASKID  Switch current context to different task (e.g. 'use c04d8c5c7582efb4')\n"
            msg += "data        Retrieve and show data for current task\n"
            msg += "log         Retrieve and show log for current task\n"
            msg += "status      Retrieve and show status for current task\n"
            msg += "stop        Stop current task\n"
            msg += "kill        Kill current task\n"
            msg += "list        Display all tasks\n"
            msg += "flush       Flush tasks (delete all tasks)\n"
            msg += "exit        Exit this client\n"

            dataToStdout(msg)

        elif command:
            logger.error("Unknown command '%s'" % command)
def client ( host = RESTAPI_SERVER_HOST , port = RESTAPI_SERVER_PORT ) : addr = "http://%s:%d" % ( host , port ) logger . info ( "Starting REST-JSON API client to '%s'..." % addr ) try : _client ( addr ) except Exception , ex : if not isinstance ( ex , urllib2 . HTTPError ) : errMsg = "there has been a problem while connecting to the " errMsg += "REST-JSON API server at '%s' " % addr errMsg += "(%s)" % ex logger . critical ( errMsg ) return taskid = None logger . info ( "Type 'help' or '?' for list of available commands" ) while True : try : command = raw_input ( "api%s> " % ( " (%s)" % taskid if taskid else "" ) ) . strip ( ) . lower ( ) except ( EOFError , KeyboardInterrupt ) : print break if command in ( "data" , "log" , "status" , "stop" , "kill" ) : if not taskid : logger . error ( "No task ID in use" ) continue raw = _client ( "%s/scan/%s/%s" % ( addr , taskid , command ) ) res = dejsonize ( raw ) if not res [ "success" ] : logger . error ( "Failed to execute command %s" % command ) dataToStdout ( "%s\n" % raw ) elif command . startswith ( "new" ) : if ' ' not in command : logger . error ( "Program arguments are missing" ) continue argv = [ "sqlmap.py" ] + shlex . split ( command ) [ 1 : ] try : cmdLineOptions = cmdLineParser ( argv ) . __dict__ except : taskid = None continue for key in list ( cmdLineOptions ) : if cmdLineOptions [ key ] is None : del cmdLineOptions [ key ] raw = _client ( "%s/task/new" % addr ) res = dejsonize ( raw ) if not res [ "success" ] : logger . error ( "Failed to create new task" ) continue taskid = res [ "taskid" ] logger . info ( "New task ID is '%s'" % taskid ) raw = _client ( "%s/scan/%s/start" % ( addr , taskid ) , cmdLineOptions ) res = dejsonize ( raw ) if not res [ "success" ] : logger . error ( "Failed to start scan" ) continue logger . info ( "Scanning started" ) elif command . startswith ( "use" ) : taskid = ( command . split ( ) [ 1 ] if ' ' in command else "" ) . strip ( "'\"" ) if not taskid : logger . error ( "Task ID is missing" ) taskid = None continue elif not re . search ( r"\A[0-9a-fA-F]{16}\Z" , taskid ) : logger . error ( "Invalid task ID '%s'" % taskid ) taskid = None continue logger . info ( "Switching to task ID '%s' " % taskid ) elif command in ( "list" , "flush" ) : raw = _client ( "%s/admin/%s/%s" % ( addr , taskid or 0 , command ) ) res = dejsonize ( raw ) if not res [ "success" ] : logger . error ( "Failed to execute command %s" % command ) elif command == "flush" : taskid = None dataToStdout ( "%s\n" % raw ) elif command in ( "exit" , "bye" , "quit" , 'q' ) : return elif command in ( "help" , "?" ) : msg = "help        Show this help message\n" msg += "new ARGS    Start a new scan task with provided arguments (e.g. 'new -u \"http://testphp.vulnweb.com/artists.php?artist=1\"')\n" msg += "use TASKID  Switch current context to different task (e.g. 'use c04d8c5c7582efb4')\n" msg += "data        Retrieve and show data for current task\n" msg += "log         Retrieve and show log for current task\n" msg += "status      Retrieve and show status for current task\n" msg += "stop        Stop current task\n" msg += "kill        Kill current task\n" msg += "list        Display all tasks\n" msg += "flush       Flush tasks (delete all tasks)\n" msg += "exit        Exit this client\n" dataToStdout ( msg ) elif command : logger . error ( "Unknown command '%s'" % command )