コード例 #1
0
 def reset(self):
     NUM_MACHINES_CVD = self.config['NUM_MACHINES_CVD']
     NUM_MACHINES_CDO = self.config['NUM_MACHINES_CDO']
     NUM_JOBS = self.config['NUM_JOBS']
     self.machines_cvd = [
         Machine(str(i), process='CVD') for i in range(NUM_MACHINES_CVD)
     ]
     self.machines_cdo = [
         Machine(str(i), process='CDO') for i in range(NUM_MACHINES_CDO)
     ]
     self.jobs = [Jobs(i) for i in range(NUM_JOBS)]
     self.miss_cqt = []
     self.NOW = 0
     self.jobs_processed_CVD = np.zeros(
         (self.config['NUM_MACHINES_CVD'], self.config['NUM_JOBS']),
         dtype=np.int8)
     self.jobs_processed_CDO = np.zeros(
         (self.config['NUM_MACHINES_CDO'], self.config['NUM_JOBS']),
         dtype=np.int8)
     self.process_completion_cvd = np.zeros(
         (self.config['NUM_MACHINES_CVD'], self.config['NUM_JOBS']))
     self.process_completion_cdo = np.zeros(
         (self.config['NUM_MACHINES_CDO'], self.config['NUM_JOBS']))
     self.lot_release = 0
     self.time_release = self.df_log['Time step'].values
     self.job_num = 0
     return self.returnObs()
コード例 #2
0
ファイル: main.py プロジェクト: jkucharczykone/esx-control
 def create_model(self, vm, sess):
     machine = Machine(name=vm.name,
                       vm=vm.__str__(),
                       powerState=vm.summary.runtime.powerState,
                       connectionState=vm.summary.runtime.connectionState,
                       bootTime=vm.summary.runtime.bootTime,
                       guestFullName=vm.summary.guest.guestFullName,
                       hostName=vm.summary.guest.hostName,
                       ipAddress=vm.summary.guest.ipAddress,
                       annotation=vm.summary.config.annotation,
                       memorySizeMB=vm.summary.config.memorySizeMB,
                       numCpu=vm.summary.config.numCpu,
                       numEthernetCards=vm.summary.config.numEthernetCards,
                       numVirtualDisks=vm.summary.config.numVirtualDisks,
                       uuid=vm.summary.config.uuid,
                       guestId=vm.summary.config.guestId,
                       guestFullNameConf=vm.summary.config.guestFullName)
     karty = []
     for x in vm.guest.net:
         karty.append(
             EthCard(macAddress=x.macAddress,
                     network=x.network,
                     connected=x.connected,
                     ipAddress=x.ipAddress,
                     vm=machine.vm))
     return machine, karty
コード例 #3
0
def new_machine():
    values = request.get_json()
    if not values:
        return json.dumps({"error": "please provide data with json headers"})
    result = {}
    session = None
    password = values.get("password", None)
    if not password:
        result = {"exception": "password missing"}
    else:
        if not password == entry_password:
            result = {"exception": "Wrong password"}
        else:
            try:
                ip = values.get("ip", None)
                name = values.get("name", None)
                if (not name or not ip):
                    raise Exception("IP or NAME missing !!")
                session = Session()
                m = Machine(ip=ip, name=name)
                session.add(m)
                session.commit()
                result = {"status": "success !!"}
            except Exception as ex:
                result = {"exception": str(ex)}

    if session: session.close()
    return json.dumps(result)
コード例 #4
0
ファイル: converge.py プロジェクト: appcubator/deploy
def converge(key='*'):
    # note that this gets the machines in the `key` cluster
    machines = Machine.load_files(key=key) # machine name => machine

    # note that this gets all containers accross all users.
    # we are converging the entire `key` machine group within the cluster
    containers = Container.load_files(machines) # deploy id => container

    print machines, containers

    create_threads = []
    destroy_threads = []
    
    for m in machines.values():
        target_containers = [c for c in containers.values() if c.machine == m]
        (to_create, to_delete, t1, t2) = m.converge(target_containers)
        create_threads.append(t1)
        destroy_threads.append(t2)

    print "Starting container creation"
    for t in create_threads:
        t.start()

    for t in create_threads:
        t.join()
    print "Finished container creation"

    print "Starting container destruction"
    for t in destroy_threads:
        t.start()

    for t in destroy_threads:
        t.join()
    print "Finished container destruction"
コード例 #5
0
def test_customer_update(db):
    machine = Machine()
    customer_name = "Cellcom"
    machineid = '1590'

    machine.query.update_customer(machineid=machineid,
                                  customer_name=customer_name)
コード例 #6
0
ファイル: sleep.py プロジェクト: appcubator/deploy
def sleep(key='alpha-dev'):
    machines = Machine.load_files(key=key) # machine name => machine
    print machines
    containers = Container.load_files(machines, key='*') # deploy id => container

    for m in machines.values():
        target_containers = [c for c in containers.values() if c.machine == m and c.d_id not in ['zenrez','adshare']]
        m.bulk_sleep(target_containers)
コード例 #7
0
def get_machines(product_type: str = None, water_line_compatible: bool = None):
    machines = [
        Machine(sku=machine["sku"],
                product_type=machine["product_type"],
                water_line_compatible=machine["water_line_compatible"])
        for machine in data.products["machines"]
        if (product_type is None or machine["product_type"] == product_type)
        and (water_line_compatible is None
             or machine["water_line_compatible"] == water_line_compatible)
    ]
    return machines
コード例 #8
0
	def get(self):
		self.response.headers['Content-Type'] = 'text/plain'
		rfid = self.request.get('rfid')
		machine_name = self.request.get('machine')
		machine = Machine.all().filter('type',machine_name).get()
		user = RFID.fetch_member(rfid)
		valid = machine and machine.authorize(user, 'use')
		if valid:
			machine.begin_use(user, 'use')
			out = 1
		else:
			out = 0
		self.response.out.write(out)
コード例 #9
0
ファイル: main.py プロジェクト: dnewcome/hd-toys
	def get(self):
		self.response.headers['Content-Type'] = 'text/plain'
		rfid = self.request.get('rfid')
		machine_name = self.request.get('machine')
		machine = Machine.all().filter('type',machine_name).get()
		user = RFID.fetch_member(rfid)
		valid = machine and machine.authorize(user, 'use')
		if valid:
			machine.begin_use(user, 'use')
			out = 1
		else:
			out = 0
		self.response.out.write(out)
コード例 #10
0
 def post(self):
     data = request.get_json()
     try:
         new_data = Machine(port=data['port'],
                            root_path=data['root_path'],
                            max_capacity=data['max_capacity'],
                            left_capacity=data['left_capacity'])
         s.add(new_data)
         s.commit()
     except Exception as e:
         print(e)
         abort(500)
     return jsonify({'successfully created data': True})
コード例 #11
0
def test_machine_create(db):
    m = Machine()
    iboxes = [
        dict(
            name='ibox1590',
            machineid='1590',
            ticket='MAN-1223',
            owner='*****@*****.**',
            iboxmodel='F6XXX',
        ),
        dict(
            name='ibox1692',
            machineid='1692',
            ticket='MAN-1245',
            owner='*****@*****.**',
            iboxmodel='F4XXX',
        ),
    ]

    for ibox in iboxes:
        rowid = m.add(ibox)
        print("Row ID: {}".format(rowid))
        assert type(rowid).__name__ == 'int'
コード例 #12
0
def add_machine():
    if request.method == 'GET':
        user_id = session.get('user_id')
        current_user = User.query.filter(User.id == user_id).first()
        if current_user:
            return render_template('addMachine.html')
        else:
            return redirect(url_for('login'))
    else:
        name = request.form.get('name')
        user_id = session.get('user_id')
        custodian = request.form.get('custodian')

        operating_system = request.form.get('operation_system')
        operating_system_version = request.form.get('operation_system_version')
        color = request.form.get('color')
        # 保存操作系统的变量
        operating_system_r = 0
        if "苹果" in operating_system:
            operating_system_r = 0
        elif "安卓" in operating_system:
            operating_system_r = 1
        else:
            operating_system_r = 2
        # 保存手机的颜色
        color_r = 0
        if "白" in color:
            color_r = 0
        elif "黑" in color:
            color_r = 1
        elif "金" in color:
            color_r = 2
        else:
            color_r = 3
        machine = Machine(custodian_id=user_id,
                          status=0,
                          name=name,
                          operating_system=operating_system_r,
                          operating_system_version=operating_system_version,
                          color=color_r)
        db.session.add(machine)
        db.session.commit()
        return redirect(url_for('index'))
コード例 #13
0
ファイル: views.py プロジェクト: vovamumchur/managedmacadmin
def submit(request):
    if request.method == 'POST':
        submit = request.POST
    elif request.method == 'GET':
        submit = request.GET
    else:
        raise Http404

    mac = submit.get('mac')
    machine = None
    if mac:
        try:
            machine = Machine.objects.get(mac=mac)
        except Machine.DoesNotExist:
            machine = Machine(mac=mac)

    if machine:
        if submit.get('hostname'):
            machine.hostname = submit.get('hostname')
        machine.last_checkin = timezone.now()
        machine.save()

        response = ''

        facts = submit.get('Facts')
        if facts is not None:
            facts = json.loads(facts)
            for key in facts:
                try:
                    fact = Fact.objects.get(machine=machine, name=key)
                except:
                    fact = Fact(machine=machine, name=key)
                fact.last_update = timezone.now()
                fact.value = facts[key]

                fact.save()

        facts = submit.get('HistoricalFacts')
        if facts is not None:
            facts = json.loads(facts)
            for key in facts:
                fact = HistoricalFact(machine=machine, name=key)
                fact.timestamp = timezone.now()
                fact.value = facts[key]

                fact.save()

        return HttpResponse('Report submitted.\n')

    return HttpResponse('Report not submitted.\n')
コード例 #14
0
ファイル: views.py プロジェクト: mjung/munkiwebadmin
def submit(request, submission_type):
    if request.method != 'POST':
        raise Http404
    
    submit = request.POST
    mac = submit.get('mac')
    client = None
    if mac:
        try:
            machine = Machine.objects.get(mac=mac)
        except Machine.DoesNotExist:
            machine = Machine(mac=mac)
    if machine:
        try:
            report = MunkiReport.objects.get(machine=machine)
        except MunkiReport.DoesNotExist:
            report = MunkiReport(machine=machine)
    
    if machine and report:
        machine.hostname = submit.get('name', '<NO NAME>')
        machine.remote_ip = request.META['REMOTE_ADDR']
        machine.last_munki_update = datetime.now()
        if 'username' in submit:
            machine.username = submit.get('username')
        if 'location' in submit:
            machine.location = submit.get('location')
        
        report.runtype = submit.get('runtype')
        report.timestamp = datetime.now()
        
        if submission_type == 'postflight':
            report.runstate = u"done"
            if 'base64bz2report' in submit:
                report.update_report(submit.get('base64bz2report'))

            # extract machine data from the report
            report_data = report.get_report()
            if 'MachineInfo' in report_data:
                machine.os_version = report_data['MachineInfo'].get(
                    'os_vers', 'UNKNOWN')
                machine.cpu_arch = report_data['MachineInfo'].get(
                    'arch', 'UNKNOWN')
            machine.available_disk_space = \
                report_data.get('AvailableDiskSpace') or 0
            hwinfo = {}
            if 'SystemProfile' in report_data.get('MachineInfo', []):
                for profile in report_data['MachineInfo']['SystemProfile']:
                    if profile['_dataType'] == 'SPHardwareDataType':
                        hwinfo = profile._items[0]
                        break
            if hwinfo:
                machine.machine_model = hwinfo.get('machine_model') and hwinfo.get('machine_model') or u'unknown'
                machine.cpu_type = hwinfo.get('cpu_type') and hwinfo.get('cpu_type') or u'unknown'
                machine.cpu_speed = hwinfo.get('current_processor_speed') and hwinfo.get('current_processor_speed') or u'0'
                machine.ram = hwinfo.get('physical_memory') and hwinfo.get('physical_memory') or u'0'
                machine.serial_number = hwinfo.get('serial_number') and hwinfo.get('serial_number')[0:15] or u'unknown'
            
            machine.save()
            report.save()
            return HttpResponse("Postflight report submmitted for %s.\n" 
                                 % submit.get('name'))
        
        if submission_type == 'preflight':
            report.runstate = u"in progress"
            report.activity = report.encode(
                {"Updating": "preflight"})
            machine.save()
            report.save()
            return HttpResponse(
                "Preflight report submmitted for %s.\n" %
                 submit.get('name'))
    
        if submission_type == 'report_broken_client':
            report.runstate = u"broken client"
            report.report = None
            report.errors = 1
            report.warnings = 0
            machine.save()
            report.save()
            return HttpResponse(
                "Broken client report submmitted for %s.\n" %
                 submit.get('name'))
    
    return HttpResponse("No report submitted.\n")
コード例 #15
0
ファイル: machine_test.py プロジェクト: h2bot/hd-toys
 def test_machine_creation(self):
     machine = Machine(name='Chainsaw', type="test_machine")
     self.assertTrue(machine.name, 'Chainsaw')
コード例 #16
0
def test_machine_queries_object(db):
    machine = Machine()
    assert hasattr(machine, 'query')
    assert hasattr(machine.query, 'db')
    assert hasattr(machine.query.db, 'cursor')
    assert type(machine.query.db.cursor).__name__ == 'DictCursor'
コード例 #17
0
ファイル: machine_test.py プロジェクト: h2bot/hd-toys
 def test_machine_requires_name(self):
     machine = Machine()
     machine.put()
コード例 #18
0
ファイル: views.py プロジェクト: ox-it/manana
def submit(request, submission_type):
    if request.method != "POST":
        raise Http404

    submit = request.POST
    serial = submit.get("serial")
    mac = submit.get("mac")
    client = None
    if serial:
        try:
            machine = Machine.objects.get(serial_number=serial)
        except Machine.DoesNotExist:
            machine = Machine(serial_number=serial)
    if machine:
        try:
            report = MunkiReport.objects.get(machine=machine)
        except MunkiReport.DoesNotExist:
            report = MunkiReport(machine=machine)

    if machine and report:
        machine.hostname = submit.get("name", "<NO NAME>")
        machine.remote_ip = request.META["REMOTE_ADDR"]
        machine.last_munki_update = datetime.now()
        if "username" in submit:
            machine.username = submit.get("username")
        if "location" in submit:
            machine.location = submit.get("location")

        report.runtype = submit.get("runtype")
        report.timestamp = datetime.now()

        if submit.get("unit"):
            unit = BusinessUnit.objects.get(hash=submit.get("unit"))
            machine.businessunit = unit

        if submission_type == "postflight":
            report.runstate = u"done"
            if "base64bz2report" in submit:
                report.update_report(submit.get("base64bz2report"))

            # extract machine data from the report
            report_data = report.get_report()
            if "MachineInfo" in report_data:
                machine.os_version = report_data["MachineInfo"].get("os_vers", machine.os_version)
                machine.cpu_arch = report_data["MachineInfo"].get("arch", machine.cpu_arch)

            machine.available_disk_space = report_data.get("AvailableDiskSpace") or machine.available_disk_space

            hwinfo = {}
            if "SystemProfile" in report_data.get("MachineInfo", []):
                for profile in report_data["MachineInfo"]["SystemProfile"]:
                    if profile["_dataType"] == "SPHardwareDataType":
                        hwinfo = profile._items[0]
                        break
            if hwinfo:
                machine.machine_model = (
                    hwinfo.get("machine_model") and hwinfo.get("machine_model") or machine.machine_model
                )
                machine.cpu_type = hwinfo.get("cpu_type") and hwinfo.get("cpu_type") or machine.cpu_type
                machine.cpu_speed = (
                    hwinfo.get("current_processor_speed") and hwinfo.get("current_processor_speed") or machine.cpu_speed
                )
                machine.ram = hwinfo.get("physical_memory") and hwinfo.get("physical_memory") or machine.ram
                machine.mac = mac

            machine.save()
            report.save()
            return HttpResponse("Postflight report submmitted for %s.\n" % submit.get("name"))

        if submission_type == "preflight":
            report.runstate = u"in progress"
            report.activity = report.encode({"Updating": "preflight"})
            machine.save()
            report.save()
            return HttpResponse("Preflight report submmitted for %s.\n" % submit.get("name"))

        if submission_type == "report_broken_client":
            report.runstate = u"broken client"
            # report.report = None
            report.errors = 1
            report.warnings = 0
            machine.save()
            report.save()
            return HttpResponse("Broken client report submmitted for %s.\n" % submit.get("name"))

    return HttpResponse("No report submitted.\n")
コード例 #19
0
ファイル: views.py プロジェクト: SteveKueng/munkiwebadmin
def staging(request, serial):
    if request.method == 'POST':
        submit = request.POST
        workflow = submit.get('workflow')
        runtype = submit.get('type')

        if serial:
            try:
                machine = Machine.objects.get(serial_number=serial)
            except Machine.DoesNotExist:
                machine = Machine(serial_number=serial)
        else:
            raise Http404

        if runtype == "save":
            if workflow == "no workflow":
                machine.imagr_workflow = ""
                machine.imagr_status = ""
                machine.imagr_message = ""
            else:
                machine.imagr_workflow = workflow
            machine.save()
            return HttpResponse("OK!")
        elif runtype == "load":
            imagr_status = machine.imagr_status
            imagr_message = machine.imagr_message

            c = RequestContext(request,{'imagr_status': imagr_status,
                                        'imagr_message': imagr_message
                                        })
            c.update(csrf(request))
            return render_to_response('reports/staging_status.html', c)
    else:
        machine = None
        if serial:
            try:
                machine = Machine.objects.get(serial_number=serial)
            except Machine.DoesNotExist:
                raise Http404
        else:
            raise Http404

        imagr_workflow = machine.imagr_workflow
        #imagr_target = machine.imagr_target

        error = None
        workflows = {}
        imagr_config_plist = ""

        if IMAGR_CONFIG_URL:
            try:
                config = urllib.urlopen(IMAGR_CONFIG_URL)
                imagr_config_plist = config.read()
                imagr_config_plist = plistlib.readPlistFromString(imagr_config_plist)
            except:
                error = "Can't reach server!"
        else:
            error = "Imagr URL not defined!"

        c = RequestContext(request,{'imagr_workflow': imagr_workflow,
                                   #'imagr_target': imagr_target,
                                   'workflows': workflows,
                                   'error': error,
                                   'imagr_config_plist': imagr_config_plist,
                                   'machine_serial': serial,
                                   'page': 'reports'})

        c.update(csrf(request))
        return render_to_response('reports/staging.html', c)
コード例 #20
0
ファイル: views.py プロジェクト: SteveKueng/munkiwebadmin
def submit(request, submission_type):
    if request.method != 'POST':
        return HttpResponse("No report submitted.\n")
        #raise Http404

    submit = request.POST
    serial = submit.get('serial')

    client = None
    if serial:
        try:
            machine = Machine.objects.get(serial_number=serial)
        except Machine.DoesNotExist:
            machine = Machine(serial_number=serial)
    if machine:
        try:
            report = MunkiReport.objects.get(machine=machine)
        except MunkiReport.DoesNotExist:
            report = MunkiReport(machine=machine)

    if machine and report:
        if 'mac' in submit:
            mac = submit.get('mac')

        machine.remote_ip = request.META['REMOTE_ADDR']
        if 'name' in submit:
            machine.hostname = submit.get('name')

        if 'username' in submit:
            machine.username = submit.get('username')
        if 'location' in submit:
            machine.location = submit.get('location')

        report.runtype = submit.get('runtype', 'UNKNOWN')
        report.timestamp = datetime.now()

        if submit.get('unit'):
            unit = BusinessUnit.objects.get(hash=submit.get('unit'))
            machine.businessunit = unit

        if submission_type == 'reportimagr':
            if submit.get('status'):
                machine.imagr_status = submit.get('status')
            if submit.get('message'):
                machine.imagr_message = submit.get('message')

            # delete pending workflow if successful ended
            if submit.get('status') == 'success':
                machine.imagr_workflow = ""

            report.runstate = u"imagr"
            machine.save()
            report.save()
            return HttpResponse(
                "Imagr report submmitted for %s.\n" %
                 submit.get('serial'))

        machine.last_munki_update = datetime.now()
        if submission_type == 'postflight':
            report.runstate = u"done"
            if 'base64bz2report' in submit:
                report.update_report(submit.get('base64bz2report'))

            # extract machine data from the report
            report_data = report.get_report()
            if 'MachineInfo' in report_data:
                machine.os_version = report_data['MachineInfo'].get(
                    'os_vers', machine.os_version)
                machine.cpu_arch = report_data['MachineInfo'].get(
                    'arch', machine.cpu_arch)


            machine.available_disk_space = \
                report_data.get('AvailableDiskSpace') or machine.available_disk_space

            hwinfo = {}
            if 'SystemProfile' in report_data.get('MachineInfo', []):
                for profile in report_data['MachineInfo']['SystemProfile']:
                    if profile['_dataType'] == 'SPHardwareDataType':
                        hwinfo = profile._items[0]
                        break
            if hwinfo:
                machine.machine_model = hwinfo.get('machine_model') and hwinfo.get('machine_model') or machine.machine_model
                machine.cpu_type = hwinfo.get('cpu_type') and hwinfo.get('cpu_type') or machine.cpu_type
                machine.cpu_speed = hwinfo.get('current_processor_speed') and hwinfo.get('current_processor_speed') or machine.cpu_speed
                machine.ram = hwinfo.get('physical_memory') and hwinfo.get('physical_memory') or machine.ram
                machine.mac = mac

            machine.save()
            report.save()
            return HttpResponse("Postflight report submmitted for %s.\n"
                                 % submit.get('name'))

        if submission_type == 'preflight':
            report.runstate = u"in progress"
            report.activity = report.encode(
                {"Updating": "preflight"})
            machine.save()
            report.save()
            return HttpResponse(
                "Preflight report submmitted for %s.\n" %
                 submit.get('name'))

        if submission_type == 'report_broken_client':
            report.runstate = u"broken client"
            #report.report = None
            report.errors = 1
            report.warnings = 0
            machine.save()
            report.save()
            return HttpResponse(
                "Broken client report submmitted for %s.\n" %
                 submit.get('name'))

    return HttpResponse("No report submitted.\n")
コード例 #21
0
	def test_isolation(self):
		machine = Machine(name='Chainsaw', type="test_machine")
		machine.put()
		self.assertEqual(Machine.all().count(), 1)
コード例 #22
0
	def test_isolation_again(self):
		machine = Machine(name='Tesla Coil', type='test_machine')
		machine.put()
		self.assertEqual(Machine.all().count(), 1)
コード例 #23
0
ファイル: main.py プロジェクト: raistlinJ/CyberDG
def new_machine(scenario_id):
    if request.method == 'POST':
        form = NewMachineForm(request.form)
        logger.info(request.form)
        if not form.validate() or not is_pyro_running():
            flash_form_errors(form)
            os_list = OS.query.all()
            exploits, vulns = get_files_from_scenario(scenario_id)
            return render_template('configMachine.html',
                                   scenario_id=scenario_id,
                                   os_list=os_list,
                                   machine_types=MachineTypeEnum,
                                   network_types=NetworkTypeEnum,
                                   form=form,
                                   exploits=exploits,
                                   vulns=vulns)
        rdp_ip = get_rdp_ip()
        machine = Machine(name=form.name.data,
                          machine_ip='',
                          rdp_ip=rdp_ip,
                          rdp_port=5000,
                          machine_type=form.machine_type.data,
                          processors=form.processors.data,
                          memory=form.memory.data,
                          scenario_id=scenario_id,
                          os_id=form.vm_os.data,
                          network_type=form.network_type.data,
                          cmd_line=form.cmd_line.data,
                          cmd_order=form.cmd_order.data)
        if form.network_name:
            machine.network_name = form.network_name.data
        files = get_files(form.exploits.data, form.vulns.data)
        machine.file = files
        db.session.add(machine)
        db.session.commit()

        scenario = Scenario.query.filter_by(id=scenario_id).first()
        machine1 = Machine.query.filter_by(id=machine.id).first()

        machine1.machine_ip = machine_gen.generate_ip(scenario.id, machine1.id)
        machine1.rdp_port = machine_gen.generate_port(machine.id)
        db.session.commit()

        rdpManager = RDPManager(username=scenario.id, password=scenario.id)
        rdpManager.add_connection(name=machine.id,
                                  username=machine.machine_username,
                                  password=machine.machine_password,
                                  hostname=machine.rdp_ip,
                                  port=machine.rdp_port)

        connection_id = rdpManager.get_connection_id(str(machine.id))
        connection_link = rdpManager.get_connection_link(connection_id)
        machine.connection_link = connection_link
        machine.connection_id = connection_id
        db.session.commit()

        flash("Machine created", 'success')
        return redirect(url_for('configure', id=scenario_id))
    if request.method == 'GET':
        is_pyro_running()
        os_list = OS.query.all()
        exploits, vulns = get_files_from_scenario(scenario_id)
        return render_template('configMachine.html',
                               scenario_id=scenario_id,
                               os_list=os_list,
                               machine_types=MachineTypeEnum,
                               network_types=NetworkTypeEnum,
                               exploits=exploits,
                               vulns=vulns)
コード例 #24
0
def staging(request, serial):
    if request.method == 'POST':
        submit = request.POST
        workflow = submit.get('workflow')
        runtype = submit.get('type')

        if serial:
            try:
                machine = Machine.objects.get(serial_number=serial)
            except Machine.DoesNotExist:
                machine = Machine(serial_number=serial)
        else:
            raise Http404

        if runtype == "save":
            if workflow == "no workflow":
                machine.imagr_workflow = ""
                machine.imagr_status = ""
                machine.imagr_message = ""
            else:
                machine.imagr_workflow = workflow
            machine.save()
            return HttpResponse("OK!")
        elif runtype == "load":
            imagr_status = machine.imagr_status
            imagr_message = machine.imagr_message

            c = RequestContext(request, {
                'imagr_status': imagr_status,
                'imagr_message': imagr_message
            })
            c.update(csrf(request))
            return render_to_response('reports/staging_status.html', c)
    else:
        machine = None
        if serial:
            try:
                machine = Machine.objects.get(serial_number=serial)
            except Machine.DoesNotExist:
                raise Http404
        else:
            raise Http404

        imagr_workflow = machine.imagr_workflow
        #imagr_target = machine.imagr_target

        error = None
        workflows = {}
        imagr_config_plist = ""

        if IMAGR_CONFIG_URL:
            try:
                config = urllib.urlopen(IMAGR_CONFIG_URL)
                imagr_config_plist = config.read()
                imagr_config_plist = plistlib.readPlistFromString(
                    imagr_config_plist)
            except:
                error = "Can't reach server!"
        else:
            error = "Imagr URL not defined!"

        c = RequestContext(
            request,
            {
                'imagr_workflow': imagr_workflow,
                #'imagr_target': imagr_target,
                'workflows': workflows,
                'error': error,
                'imagr_config_plist': imagr_config_plist,
                'machine_serial': serial,
                'page': 'reports'
            })

        c.update(csrf(request))
        return render_to_response('reports/staging.html', c)
コード例 #25
0
engine = create_engine('mysql+mysqldb://root:[email protected]:3306/test')

# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
# A DBSession() instance establishes all conversations with the database
# and represents a "staging zone" for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()

# Insert a Person in the person table
# new_person = Person(name='new person')
# session.add(new_person)
# session.commit()

new_machine = Machine(name='My Super')
session.add(new_machine)
session.commit()

# # Insert an Address in the address table
# new_address = Address(post_code='00000', person=new_person)
# session.add(new_address)
# session.commit()
コード例 #26
0
ファイル: machine_test.py プロジェクト: Yuffster/hd-toys
	def test_machine_requires_name(self):
		machine = Machine()
		machine.put()
コード例 #27
0
ファイル: views.py プロジェクト: oucsaw/manana
def submit(request, submission_type):
    if request.method != 'POST':
        raise Http404

    submit = request.POST
    serial = submit.get('serial')
    mac = submit.get('mac')
    client = None
    if serial:
        try:
            machine = Machine.objects.get(serial_number=serial)
        except Machine.DoesNotExist:
            machine = Machine(serial_number=serial)
    if machine:
        try:
            report = MunkiReport.objects.get(machine=machine)
        except MunkiReport.DoesNotExist:
            report = MunkiReport(machine=machine)

    if machine and report:
        machine.hostname = submit.get('name', '<NO NAME>')
        machine.remote_ip = request.META['REMOTE_ADDR']
        machine.last_munki_update = datetime.now()
        if 'username' in submit:
            machine.username = submit.get('username')
        if 'location' in submit:
            machine.location = submit.get('location')

        report.runtype = submit.get('runtype')
        report.timestamp = datetime.now()

        if submit.get('unit'):
            unit = BusinessUnit.objects.get(hash=submit.get('unit'))
            machine.businessunit = unit

        if submission_type == 'postflight':
            report.runstate = u"done"
            if 'base64bz2report' in submit:
                report.update_report(submit.get('base64bz2report'))

            # extract machine data from the report
            report_data = report.get_report()
            if 'MachineInfo' in report_data:
                machine.os_version = report_data['MachineInfo'].get(
                    'os_vers', machine.os_version)
                machine.cpu_arch = report_data['MachineInfo'].get(
                    'arch', machine.cpu_arch)


            machine.available_disk_space = \
                report_data.get('AvailableDiskSpace') or machine.available_disk_space

            hwinfo = {}
            if 'SystemProfile' in report_data.get('MachineInfo', []):
                for profile in report_data['MachineInfo']['SystemProfile']:
                    if profile['_dataType'] == 'SPHardwareDataType':
                        hwinfo = profile._items[0]
                        break
            if hwinfo:
                machine.machine_model = hwinfo.get(
                    'machine_model') and hwinfo.get(
                        'machine_model') or machine.machine_model
                machine.cpu_type = hwinfo.get('cpu_type') and hwinfo.get(
                    'cpu_type') or machine.cpu_type
                machine.cpu_speed = hwinfo.get(
                    'current_processor_speed') and hwinfo.get(
                        'current_processor_speed') or machine.cpu_speed
                machine.ram = hwinfo.get('physical_memory') and hwinfo.get(
                    'physical_memory') or machine.ram
                machine.mac = mac

            machine.save()
            report.save()
            return HttpResponse("Postflight report submmitted for %s.\n" %
                                submit.get('name'))

        if submission_type == 'preflight':
            report.runstate = u"in progress"
            report.activity = report.encode({"Updating": "preflight"})
            machine.save()
            report.save()
            return HttpResponse("Preflight report submmitted for %s.\n" %
                                submit.get('name'))

        if submission_type == 'report_broken_client':
            report.runstate = u"broken client"
            #report.report = None
            report.errors = 1
            report.warnings = 0
            machine.save()
            report.save()
            return HttpResponse("Broken client report submmitted for %s.\n" %
                                submit.get('name'))

    return HttpResponse("No report submitted.\n")
コード例 #28
0
ファイル: main.py プロジェクト: raistlinJ/CyberDG
def new_scenario():
    exploits = File.query.filter_by(file_type=FileTypeEnum.pov).all()
    vulns = File.query.filter_by(file_type=FileTypeEnum.vuln).all()
    if request.method == 'GET':
        is_pyro_running()
        return render_template('newScenario.html',
                               exploits=exploits,
                               vulns=vulns)
    else:
        form = NewScenarioForm(request.form)
        logger.info(request.form)
        if not is_pyro_running():
            return render_template('newScenario.html',
                                   exploits=exploits,
                                   vulns=vulns,
                                   form=form)
        if not form.validate():
            logger.info(form.errors)
            flash_form_errors(form)
            return render_template('newScenario.html',
                                   exploits=exploits,
                                   vulns=vulns,
                                   form=form)

        scenario = Scenario(name=form.name.data,
                            description=form.description.data,
                            cve_number=form.cve_number.data)

        files = get_files(form.exploits.data, form.vulns.data)
        scenario.file = files

        db.session.add(scenario)
        db.session.commit()
        rdpManager = RDPManager()
        rdpManager.add_user(scenario.id, scenario.id)
        guacUser = GuacUser(guac_username=scenario.id,
                            guac_password=scenario.id,
                            scenario_id=scenario.id)
        db.session.add(guacUser)
        db.session.commit()
        exploits = form.exploits.data

        for index, exploit in enumerate(exploits):
            f = File.query.filter_by(name=exploit).first()
            if f:
                rdp_ip = get_rdp_ip()
                os_rec = scenario_gen.generate_os_rec(f)
                rec_machine = Machine(name=scenario.name + '-Exploits' +
                                      str(index + 1),
                                      scenario_id=scenario.id,
                                      rdp_ip=rdp_ip)
                rec_machine.file.append(f)
                db.session.add(rec_machine)
                db.session.commit()

                machine_gen.generate(scenario, rec_machine, os_rec, vulns)
                db.session.commit()
                rdpManager = RDPManager(username=scenario.id,
                                        password=scenario.id)
                rdpManager.add_connection(
                    name=rec_machine.id,
                    username=rec_machine.machine_username,
                    password=rec_machine.machine_password,
                    hostname=rec_machine.rdp_ip,
                    port=rec_machine.rdp_port)
                print(scenario.id)
                # machine_gen.generate(scenario, rec_machine, os_rec, vulns)
                # db.session.commit()
                connection_id = rdpManager.get_connection_id(
                    str(rec_machine.id))
                connection_link = rdpManager.get_connection_link(connection_id)
                # print(connection_link)
                rec_machine.connection_link = connection_link
                rec_machine.connection_id = connection_id
                db.session.commit()

        return redirect(url_for('configure', id=scenario.id))