示例#1
0
def bad_request_json_response(message='', status=None):
    data = dict(message=message)
    resp = Response()
    resp.status_code = status or 400
    resp.content_type = 'application/json'
    resp.data = json.dumps(data)
    return resp
示例#2
0
文件: views.py 项目: IDEHCO3/bc_edgv
 def get(self, request, *args, **kwargs):
     contextdata = {
         "@context": getHydraVocab()
     }
     response = Response(data=contextdata)
     if request.accepted_media_type != "text/html":
         response.content_type = "application/ld+json"
     return response
示例#3
0
 def consulta_paciente(self, cpf):
     cpf = validacao_cpf(entrada['cpf'])
     query = Cliente.objects.filter(cpf=cpf)
     if query.count() > 0:
         cliente = query[0]
     r = Response(dates2(cliente.nome), )
     r.content_type = 'application/json; charset=UTF-8'
     print(r.content_type)
     return r
示例#4
0
def stopPid(request):

    res = os.popen("ps -ef|grep ansible-playbook | grep var.yaml | grep -v 'grep'| awk '{print $2}'")
    pids = res.readlines()
    for pid in pids:
        command = 'kill -9' + ' ' + pid
        subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    response = Response({"success": True, "msg": 'succ', "pid": pids})
    response.content_type = "text/html;charset=utf-8"

    return response
示例#5
0
 def get(self, request, name, content_type=None):
     method = request.method
     if name not in settings.STUB:
         raise Exception("'%s' stub have no configuration" % name)
     stub = settings.STUB[name]
     if method not in stub:
         raise Exception("'%s' stub have no configuration for %s method" %
                         (name, method))
     data = stub[method]
     response = Response(data)
     if content_type is not None:
         response.content_type = content_type
     return response
示例#6
0
文件: views.py 项目: IDEHCO3/munic
    def get(self, request, *args, **kwargs):
        classname = kwargs.get('classname')
        try:
            classobject = Class.objects.get(name=classname)
        except:
            return Response(data={})

        contextdata = ContextSerializer(classobject).data
        hydradata = HydraSerializer(classobject, request).data
        if "@context" in hydradata:
            hydradata["@context"].update(contextdata["@context"])
        contextdata.update(hydradata)
        response = Response(data=contextdata)
        if request.accepted_media_type != "text/html":
            response.content_type = "application/ld+json"
        return response
示例#7
0
def check(request):

    log = ""
    msg = ""
    information = ""
    curDir = "{0}/".format(settings.BASE_DIR.rstrip("/"))
    fileNameLog = 'opsgrat_setup.log'
    filePathLog = curDir + fileNameLog
    path = "{0}/opsgrat_setup.log".format(settings.BASE_DIR.rstrip("/"))
    if os.path.exists(path):
        with open(path, 'r') as f:
            log = f.read()

    fileCheckName = "check.txt"
    filePathCheck = curDir + fileCheckName
    if os.path.exists(filePathCheck):
        with open(filePathCheck, 'r') as cf:
            checks = cf.readlines()

            try:
                for check in checks:
                    if psutil.Process(int(check)).is_running() == True:
                        msg = True
                        break
            except:
                msg = False
    print msg

    if msg == False and os.path.exists(filePathCheck):
        os.remove(filePathCheck)

    pattern = re.compile(r'(?<=failed=)\d+\.?\d*')
    check_logs = pattern.findall(log)
    try:
        for check_log in check_logs:
            if check_log == '0':
                information = True
            else:
                information = False
    except:
        information = False

    response = Response({"success": True, "msg": 'succ', "is_running": msg, "log": log, "information": information})
    response.content_type = "text/html;charset=utf-8"

    return response
示例#8
0
def setupSshPass(request):

    command = 'pip install sshpass'
    subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res = os.popen("ps -ef|grep pip | grep sshpass| grep -v 'grep'| awk '{print $2}'")
    pid = res.read()

    curDir = "{0}/".format(settings.BASE_DIR.rstrip("/"))
    CheckSshPassName = "check_sshpass.txt"
    PathCheckSshPass = curDir + CheckSshPassName
    with open(PathCheckSshPass, 'wb') as pc:
            pc.write(str(pid))

    response = Response({"success": True, "msg": 'succ', "pid": pid})
    response.content_type = "text/html;charset=utf-8"

    return response
示例#9
0
文件: views.py 项目: jadkorr/PTART
def attachment_raw(request, pk) :
    response = None
    try:
        item = Attachment.objects.get(pk=pk)
        if item.is_user_can_view(request.user) :
            response = Response(item.get_raw_data())
            response.content_type = "application/octet-stream"
            response['Content-Disposition'] = 'attachment; filename=' + item.attachment_name
        else :
            response = Response(status=status.HTTP_403_FORBIDDEN)
    except Attachment.DoesNotExist:
        response = Response(status=status.HTTP_404_NOT_FOUND)
        
    response.accepted_renderer = BinaryRenderer()
    response.accepted_media_type = 'application/octet-stream'
    response.renderer_context = {}
    return response
示例#10
0
def sshpass(request):

    result = ""
    curDir = "{0}/".format(settings.BASE_DIR.rstrip("/"))
    CheckSshPassName = "check_sshpass.txt"
    PathCheckSshPass = curDir + CheckSshPassName
    if os.path.exists(PathCheckSshPass):
        with open(PathCheckSshPass, 'r') as cf:
            checks = cf.readlines()

            try:
                for check in checks:
                    if psutil.Process(int(check)).is_running() == True:
                        result = True
                        break
            except:
                result = False

    if result == False and os.path.exists(PathCheckSshPass):
        os.remove(PathCheckSshPass)
    response = Response({"success": True, "msg": 'succ', "result": result})
    response.content_type = "text/html;charset=utf-8"

    return response
示例#11
0
    def get(self, request, file_name=None):

        if (not file_name):
            result = []
            for file in os.listdir(os.environ['CUT_FOLDER']):
                result.append({'file_name': '/getcut/' + file})

            return Response({'files': result}, 200)

        fs = FileSystemStorage()
        obj = fs.open(file_name)
        response = Response()
        response.status_code = 200
        #response['Content-Disposition'] = 'attachment; filename={}.jpg'.format(file_name)
        #response.write("hello")
        content = b''
        with open(file_name, 'rb') as f:
            for line in f:
                content += line

        #obj.close()
        response = Response(content)
        response.content_type = 'image/jpeg'
        return response
示例#12
0
def setup(request):

    opsgrat_user = request.POST.get('opsgrat_user')
    opsgrat_group = request.POST.get('opsgrat_group')
    install_dir = request.POST.get('install_dir')
    log_dir = request.POST.get('log_dir')
    pid_dir = request.POST.get('pid_dir')

    mysql_host = request.POST.get('mysql_host')
    mysql_port = request.POST.get('mysql_port')
    mysql_user = request.POST.get('mysql_user')
    mysql_user_password = request.POST.get('mysql_user_password')
    mysql_opsgrat_db = request.POST.get('mysql_opsgrat_db')
    mysql_sso_db = request.POST.get('mysql_sso_db')

    opsgrat_uwsgi_port = request.POST.get('opsgrat_uwsgi_port')
    opsgrat_nginx_port = request.POST.get('opsgrat_nginx_port')
    sso_nginx_port = request.POST.get('sso_nginx_port')
    sso_uwsgi_port = request.POST.get('sso_uwsgi_port')

    redis_host = request.POST.get('redis_host')
    redis_port = request.POST.get('redis_port')
    redis_passwd = request.POST.get('redis_passwd')

    rabbitmq_host = request.POST.get('rabbitmq_host')
    rabbitmq_port = request.POST.get('rabbitmq_port')
    rabbitmq_user = request.POST.get('rabbitmq_user')
    rabbitmq_passwd = request.POST.get('rabbitmq_passwd')

    data = ['opsgrat_user:'******' ' + opsgrat_user, 'opsgrat_group:' + ' ' + opsgrat_group, 'install_dir:' + ' ' + install_dir, 'log_dir:' + ' ' + log_dir, 'pid_dir:' + ' ' + pid_dir + '\n',
            'mysql_host:' + ' ' + mysql_host, 'mysql_port:' + ' ' + mysql_port, 'mysql_user:'******' ' + mysql_user, 'mysql_user_password:'******' ' + mysql_user_password, 'mysql_opsgrat_db:' + ' ' + mysql_opsgrat_db, 'mysql_sso_db:' + ' ' + mysql_sso_db + '\n',
            'opsgrat_uwsgi_port:' + ' ' + opsgrat_uwsgi_port, 'opsgrat_nginx_port:' + ' ' + opsgrat_nginx_port, 'sso_nginx_port:' + ' ' + sso_nginx_port, 'sso_uwsgi_port:' + ' ' + sso_uwsgi_port + '\n',
            'redis_host:' + ' ' + redis_host, 'redis_port:' + ' ' + redis_port, 'redis_passwd:' + ' ' + redis_passwd + '\n',
            'rabbitmq_host:' + ' ' + rabbitmq_host, 'rabbitmq_port:' + ' '+ rabbitmq_port, 'rabbitmq_user:'******' ' + rabbitmq_user, 'rabbitmq_passwd:' + ' ' + rabbitmq_passwd
            ]

    curDir = "{0}/".format(settings.BASE_DIR.rstrip("/"))

    if not os.path.exists(curDir):
        os.makedirs(curDir)

    fileName = 'var.yaml'
    filePath = curDir + fileName
    print('\n'.join(data))
    with open(filePath, "wb") as f:

        f.write('\n'.join(data))

    fileName = 'var.yaml'
    fileNameLog = 'opsgrat_setup.log'
    filePathLog = curDir + fileNameLog
    filePath = curDir + fileName
    os.path.dirname("{0}".format(settings.BASE_DIR.rstrip("/")))
    os.chdir(os.path.dirname("{0}".format(settings.BASE_DIR.rstrip("/"))))
    command ='nohup ansible-playbook -i local main.yml -e @' + filePath + ' ' + ' > ' + filePathLog + " &"
    subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res = os.popen("ps -ef|grep ansible-playbook | grep var.yaml | grep -v 'grep'| awk '{print $2}'")
    pid = res.read()

    fileCheckName = "check.txt"
    filePathCheck = curDir + fileCheckName
    with open(filePathCheck, 'wb') as pc:
            pc.write(str(pid))

    response = Response({"success": True, "msg": "succ", "data": data})
    response.content_type = "text/html;charset=utf-8"
    return response
示例#13
0
def webhook(request):

    dates = {"fulfillmentText": "Ola tudo bem"}
    date2 = ""

    def dates2(value):
        date2 = {
            "fulfillmentMessages": [
                # {

                #         "card": {
                #             "title": "card title",
                #             "subtitle": "card text",
                #             "imageUri": "https://assistant.google.com/static/images/molecule/Molecule-Formation-stop.png",
                #             "buttons": [
                #                 {
                #                     "text": "button text",
                #                     "postback": "https://assistant.google.com/"
                #                 }
                #             ]
                #         }

                # }
                {
                    "text": {
                        "text": [value]
                    },
                }
            ]
        }
        # date2 = {"fulfillmentText": value + "\n\n teste" + "/n/n teste"}

        return date2

    def consulta_paciente(self, cpf):
        cpf = validacao_cpf(entrada['cpf'])
        query = Cliente.objects.filter(cpf=cpf)
        if query.count() > 0:
            cliente = query[0]
        r = Response(dates2(cliente.nome), )
        r.content_type = 'application/json; charset=UTF-8'
        print(r.content_type)
        return r

    if request.method == 'POST':
        # converte os dados recebidos do body em formato json
        json_data = json.loads(str(request.body, encoding='utf-8'))

        # intent
        intent_name = json_data['queryResult']['intent']['displayName']
        print(intent_name)
        # esses são os parametros que solicitei do usuario
        entrada = json_data['queryResult']['parameters']
        # consulta o banco de dados e verifica se existe alguem com o cpf digitado e se houver
        # ele retorna nome e cpf
        if intent_name == "consulta.paciente":
            cpf = validacao_do_cpf(entrada['cpf'])
            query = Cliente.objects.filter(cpf=cpf)
            if query.count() > 0:
                cliente = query[0]

                r = Response(
                    dates2("Olá, " + cliente.nome + ".\nVamos agendar? "), )
                r.content_type = 'application/json; charset=UTF-8'
                return r
            else:
                r = Response(
                    {"followupEventInput": {
                        "name": "usuario_nao_cadastrado"
                    }})
                r.content_type = 'application/json; charset=UTF-8'
                return r

        if intent_name == "consulta.paciente - yes":
            print("entrei")
            r = Response(
                dates2(
                    "Qual a especialidade você deseja agendar a consulta ?"))
            r.content_type = 'application/json; charset=UTF-8'
            return r

        date2 = dates2("intent diferente")

        return Response(date2)
    return Response(date2)
示例#14
0
def project_xlsx(request, pk):
    response = None
    try:
        project = Project.objects.get(pk=pk)
        if project.is_user_can_view(request.user):

            wb = Workbook()
            ws = wb.active

            #Define column size
            wb.active.column_dimensions['A'].width = 28
            wb.active.column_dimensions['B'].width = 10
            wb.active.column_dimensions['C'].width = 10
            wb.active.column_dimensions['D'].width = 50
            wb.active.column_dimensions['E'].width = 30
            wb.active.column_dimensions['F'].width = 50

            #Add project data.
            ws['A1'] = "Project Name:"
            ws['A2'] = "Date:"
            ws['A3'] = "Auditors:"
            ws['B1'] = project.name
            ws['B2'] = project.added

            #Construct the auditor string
            pentester_str = ""
            previous = ""
            for pentester in project.pentesters.all():
                pentester_str = "{}{}{} - {} {}".format(
                    pentester_str, previous, pentester.username,
                    pentester.first_name, pentester.last_name)
                previous = ", "
            ws['B3'] = pentester_str

            #Beautify project data
            ws.merge_cells('B1:F1')
            ws.merge_cells('B2:F2')
            ws.merge_cells('B3:F3')

            projectHeaderStyle = styles.NamedStyle(name='project_header_style')
            projectHeaderStyle.font = styles.Font(name='Calibri',
                                                  size=14,
                                                  bold=True,
                                                  color='000000')
            projectHeaderStyle.fill = styles.PatternFill(patternType='solid',
                                                         fgColor='00B0F0')
            projectHeaderStyle.alignment = styles.Alignment(horizontal='left')
            ws['A1'].style = projectHeaderStyle
            ws['A2'].style = projectHeaderStyle
            ws['A3'].style = projectHeaderStyle

            projectValueStyle = styles.NamedStyle(name='project_value_style')
            projectValueStyle.font = styles.Font(name='Calibri',
                                                 size=14,
                                                 italic=True,
                                                 color='000000')
            projectValueStyle.fill = styles.PatternFill(patternType='solid',
                                                        fgColor='00B0F0')
            projectValueStyle.alignment = styles.Alignment(horizontal='left')

            ws['B1'].style = projectValueStyle
            ws['B2'].style = projectValueStyle
            ws['B3'].style = projectValueStyle
            ws['B2'].number_format = 'YYYY MMM DD'

            #Add column header.
            ws['A5'] = "Assessment"
            ws['B5'] = "Sev"
            ws['C5'] = "CVSS"
            ws['D5'] = "Title"
            ws['E5'] = "Asset"
            ws['F5'] = "Labels"

            columnHeaderStyle = styles.NamedStyle(name='column_header_style')
            columnHeaderStyle.font = styles.Font(name='Calibri',
                                                 size=12,
                                                 bold=True,
                                                 color='000000')
            columnHeaderStyle.fill = styles.PatternFill(patternType='solid',
                                                        fgColor='92D050')
            columnHeaderStyle.alignment = styles.Alignment(horizontal='center')

            ws['A5'].style = columnHeaderStyle
            ws['B5'].style = columnHeaderStyle
            ws['C5'].style = columnHeaderStyle
            ws['D5'].style = columnHeaderStyle
            ws['E5'].style = columnHeaderStyle
            ws['F5'].style = columnHeaderStyle

            #Fill the report
            criticalStyle = styles.NamedStyle(name='critical_style')
            criticalStyle.font = styles.Font(name='OCR A Extended',
                                             color='FFFFFF')
            criticalStyle.fill = styles.PatternFill(patternType='solid',
                                                    fgColor='343a40')
            criticalStyle.alignment = styles.Alignment(horizontal='center')

            highStyle = styles.NamedStyle(name='high_style')
            highStyle.font = styles.Font(name='OCR A Extended', color='FFFFFF')
            highStyle.fill = styles.PatternFill(patternType='solid',
                                                fgColor='dc3545')
            highStyle.alignment = styles.Alignment(horizontal='center')

            mediumStyle = styles.NamedStyle(name='medium_style')
            mediumStyle.font = styles.Font(name='OCR A Extended',
                                           color='212529')
            mediumStyle.fill = styles.PatternFill(patternType='solid',
                                                  fgColor='ffc107')
            mediumStyle.alignment = styles.Alignment(horizontal='center')

            lowStyle = styles.NamedStyle(name='low_style')
            lowStyle.font = styles.Font(name='OCR A Extended', color='FFFFFF')
            lowStyle.fill = styles.PatternFill(patternType='solid',
                                               fgColor='28a745')
            lowStyle.alignment = styles.Alignment(horizontal='center')

            infoStyle = styles.NamedStyle(name='info_style')
            infoStyle.font = styles.Font(name='OCR A Extended', color='FFFFFF')
            infoStyle.fill = styles.PatternFill(patternType='solid',
                                                fgColor='6c757d')
            infoStyle.alignment = styles.Alignment(horizontal='center')

            line = 6
            for assessment in project.assessment_set.all():
                for hit in assessment.displayable_hits():
                    ws.cell(row=line, column=1).value = assessment.name
                    ws.cell(row=line,
                            column=2).value = "P{}".format(hit.severity)
                    ws.cell(row=line, column=3).value = hit.get_cvss_value()
                    ws.cell(row=line, column=4).value = hit.title
                    ws.cell(row=line, column=5).value = hit.asset

                    label_str = ""
                    previous = ""
                    for label in hit.labels.all():
                        label_str = "{}{}{}".format(label_str, previous,
                                                    label.title)
                        previous = ", "
                    ws.cell(row=line, column=6).value = label_str

                    #Apply style from value.
                    if hit.severity == 1:
                        ws.cell(row=line, column=2).style = criticalStyle
                    elif hit.severity == 2:
                        ws.cell(row=line, column=2).style = highStyle
                    elif hit.severity == 3:
                        ws.cell(row=line, column=2).style = mediumStyle
                    elif hit.severity == 4:
                        ws.cell(row=line, column=2).style = lowStyle
                    elif hit.severity == 5:
                        ws.cell(row=line, column=2).style = infoStyle

                    try:
                        if float(hit.get_cvss_value()) < 4.0:
                            ws.cell(row=line, column=3).style = infoStyle
                        elif float(hit.get_cvss_value()) < 4.0:
                            ws.cell(row=line, column=3).style = lowStyle
                        elif float(hit.get_cvss_value()) < 7.0:
                            ws.cell(row=line, column=3).style = mediumStyle
                        elif float(hit.get_cvss_value()) < 9.0:
                            ws.cell(row=line, column=3).style = highStyle
                        else:
                            ws.cell(row=line, column=3).style = criticalStyle
                    except ValueError:
                        ws.cell(row=line, column=3).style = infoStyle
                    line = line + 1

            ws.auto_filter.ref = "A5:F{}".format(line)

            #Prepare HTTP response.
            response = Response(save_virtual_workbook(wb))
            response.content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            response[
                'Content-Disposition'] = 'attachment; filename=' + project.name + ".xlsx"
            response.accepted_renderer = BinaryRenderer()
            response.accepted_media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            response.renderer_context = {}

            wb.close()
        else:
            response = Response(status=status.HTTP_403_FORBIDDEN)
    except Flag.DoesNotExist:
        response = Response(status=status.HTTP_404_NOT_FOUND)
    return response