コード例 #1
0
ファイル: device.py プロジェクト: jaconsta/aquas_web
 def create(self, request):
     if not request.data.get('name'):
         return JsonResponse({'detail': 'Missing name'},
                             status=status.HTTP_400_BAD_REQUEST)
     Device.createDevice(request.user, request.data.get('name'))
     return JsonResponse({'status': 'device created'},
                         status=status.HTTP_201_CREATED)
コード例 #2
0
    def create(self, request):
        if not request.user.is_superuser:
            return HttpResponse(status=403)

        device = Device()
        device.save()
        return HttpResponse(status=200)
コード例 #3
0
    def test_should_import_devoce_data(self, api_client):
        # Given : Sample Data
        expected_device_count = 5

        # When : 해당 데이터를 database에 넣는 코드 실행
        Device.load_initial_data()

        # Then : 총 5개의 데이터가 들어가야함
        devices = Device.objects.all()
        assert expected_device_count == len(devices)
コード例 #4
0
ファイル: tests.py プロジェクト: bwghughes/roomysite
 def create_space(self):
     device = Device()
     device.name = "Device 1"
     device.registered_at = timezone.now()
     device.save()
     space = Space()
     space.device = device
     space.name = "Space 1"
     space.area = 22.5
     space.save()
     return space
コード例 #5
0
ファイル: tests.py プロジェクト: bwghughes/roomysite
    def test_creating_device_and_saving_it(self):
        device = Device()
        device.name = "Device 1"
        device.registered_at = timezone.now()
        device.save()

        # Retreive it
        all_devices = Device.objects.all()
        self.assertEquals(len(all_devices), 1)
        self.assertEquals(all_devices[0].name, "Device 1")
        self.assertIsInstance(uuid.UUID(all_devices[0].uuid), uuid.UUID)
        self.assertEquals(all_devices[0].registered_at, device.registered_at)
コード例 #6
0
 def test_device_is_related_to_location(self):
     ## 38°09'56.7"S+146°41'56.0"E
     # West and South are negative. North and East are positive
     location_ = Location.objects.create(name="Field A",
                                         longitude=-38.1665936,
                                         latitude=146.6989864,
                                         altitude=80.00)
     device = Device(name="device_a",
                     description="device description",
                     serial_id="abc",
                     address="abc")
     device.location = location_
     device.save()
     self.assertIn(device, location_.device_set.all())
コード例 #7
0
    def handle(self, *args, **options):
        err = SystemExit(
            'refused to create example objects outside of demo mode')
        try:
            if not settings.DEMO_MODE:
                raise err
        except AttributeError:
            raise err
        Lageruser.objects.create_superuser('admin', 'admin@localhost', 'admin')
        Section.objects.create(name='Headquarters')
        Building.objects.create(name='Hall A')
        Room.objects.create(name='23',
                            building=Building.objects.first(),
                            section=Section.objects.first())
        Room.objects.create(name='24',
                            building=Building.objects.first(),
                            section=Section.objects.first())

        Manufacturer.objects.create(name='Apple')
        Devicegroup.objects.create(name='Human Resources')
        Type.objects.create(name='Notebook')
        device = Device(name='MacBook Pro 15 with Retina (mid-2015)',
                        room=Room.objects.first(),
                        devicetype=Type.objects.first(),
                        manufacturer=Manufacturer.objects.first(),
                        serialnumber='C02VK000000',
                        inventorynumber='4117')
        device.save()

        Lending.objects.create(owner=Lageruser.objects.first(),
                               device=Device.objects.first(),
                               duedate=date.today() + timedelta(days=1))
        device.currentlending = Lending.objects.first()
        device.save()
コード例 #8
0
def scan():
    """
    Scan the network

    Args:
        None
    Returns:
        None
    """
    print("SCAN")
    local_scanner = network_scan.NetworkScanner(network_scan.get_local_ip())
    arp_output = local_scanner.get_devices_on_network("-sn", "-a -n")
    ips = local_scanner.format_to_get_ip(arp_output)[:-2]
    macs = local_scanner.format_to_get_mac(arp_output)[:-2]
    vendors = local_scanner.get_vendor_by_mac(macs)
    mobile, iphone, android = network_scan.NetworkScanner.detect_mobile(ips)
    print(arp_output)
    print(ips)
    print(macs)
    print(vendors)

    for i in range(len(ips)):
        device = Device()
        device.ip_address = ips[i]
        device.mac_address = macs[i]
        device.vendor = vendors[i]
        device.mobile = mobile[i]
        device.port = 22
        device, created = Device.objects.update_or_create(
            ip_address=device.ip_address,
            mac_address=device.mac_address,
            vendor=device.vendor,
            mobile=device.mobile,
            port=device.port)
コード例 #9
0
def fake_device(inventorynumber, word):
    return Device(created_at=fake.past_date(start_date="-600d"),
                  creator=Lageruser.objects.order_by('?').first(),
                  name=word.title(),
                  inventorynumber=inventorynumber,
                  serialnumber=random.randint(1, 1000),
                  manufacturer=Manufacturer.objects.order_by('?').first(),
                  devicetype=Type.objects.order_by('?').first(),
                  room=Room.objects.order_by('?').first(),
                  group=Devicegroup.objects.order_by('?').first(),
                  department=Department.objects.order_by('?').first())
コード例 #10
0
def dev_format(device: Device) -> dict:
    r = {
        "id": device.pk,
        "comment": device.comment,
        "ip_address": device.ip_address,
        "mac_addr": str(device.mac_addr),
        "dev_type_str": device.get_dev_type_display(),
    }
    if device.group:
        r.update({"gid": device.group.pk})
    return r
コード例 #11
0
def add(device_name):
    try:
        device = Device(
            name=device_name,
            address=g.data['address'],
            user_id=g.auth['sub']
        )
        db.session.add(device)
        db.session.commit()
    except IntegrityError as e:
        raise AlreadyExistsError(device_name)
    return ('', HTTPStatus.NO_CONTENT)
コード例 #12
0
    def create(self, validated_data):
        device = Device(device_id=validated_data['device_id'],
                        info=validated_data['info'])
        device.save()

        if validated_data['apps']:
            for item in validated_data['apps']:
                device.apps.add(item['id'])
            device.save()

        if validated_data['installed_apps']:
            for item in validated_data['installed_apps']:
                find = DeviceApp.objects.filter(
                    package_name=item['package_name'])
                if find.count() == 1:
                    app = find.first()
                else:
                    app = DeviceApp.objects.create(**item)
                device.installed_apps.add(app.id)
        if validated_data['white_list']:
            for item in validated_data['white_list']:
                find = DeviceApp.objects.filter(
                    package_name=item['package_name'])
                if find.count() == 1:
                    app = find.first()
                else:
                    app = DeviceApp.objects.create(**item)
                device.white_list.add(app.id)
        return device
コード例 #13
0
ファイル: createexampledata.py プロジェクト: MPIB/Lagerregal
    def handle(self, *args, **options):
        err = SystemExit('refused to create example objects outside of demo mode')
        try:
            if not settings.DEMO_MODE:
                raise err
        except AttributeError:
            raise err
        Lageruser.objects.create_superuser('admin', 'admin@localhost', 'admin')
        Section.objects.create(name='Headquarters')
        Building.objects.create(name='Hall A')
        Room.objects.create(name='23', building=Building.objects.first(),
                            section=Section.objects.first())
        Room.objects.create(name='24', building=Building.objects.first(),
                            section=Section.objects.first())

        Manufacturer.objects.create(name='Apple')
        Devicegroup.objects.create(name='Human Resources')
        Type.objects.create(name='Notebook')
        device = Device(name='MacBook Pro 15 with Retina (mid-2015)',
                        room=Room.objects.first(),
                        devicetype=Type.objects.first(),
                        manufacturer=Manufacturer.objects.first(),
                        serialnumber='C02VK000000',
                        inventorynumber='4117')
        device.save()

        Lending.objects.create(owner=Lageruser.objects.first(),
                               device=Device.objects.first(),
                               duedate=date.today() + timedelta(days=1))
        device.currentlending = Lending.objects.first()
        device.save()
コード例 #14
0
    def post(self, request, *args, **kwargs):
        data = Data()

        result = check_device(**request.POST)

        if result:
            try:
                device = Device.objects.get(device_mac=result["device_mac"])
            except Device.DoesNotExist:
                device = Device(**result)
                device.save()

            device_enabled = device.enabled
            if device_enabled:
                result = check_data(**request.POST)
                if result:
                    data.data_value = result["data_value"]
                    data.device = device
                    data.date = datetime.datetime.now(
                    )  #TODO: Device sends real datetime
                    data.save()

        return JsonResponse({'status': True})
コード例 #15
0
ファイル: otp.py プロジェクト: andrewkrug/oss2fa
    def enrollment_complete(self, enrollment, data):
        with transaction.atomic():
            assert enrollment.status == Enrollment.STATUS_IN_PROGRESS
            assert not enrollment.is_expired()

            # mark the enrollment as failed
            enrollment.status = Enrollment.STATUS_FAILED

            private_details, err = self.get_enrollment_private_details_model(
                enrollment.private_details)
            if err:
                logger.error(
                    'failed to retrieve private details for OTP enrollment `{0}`: {1}'
                    .format(enrollment.pk, err))
                return False, err

            # create the provisioning uri
            totp = pyotp.TOTP(s=private_details['secret'],
                              digits=private_details['digits'],
                              interval=private_details['interval'])

            ok = totp.verify(data['token'],
                             valid_window=self._configuration['valid_window'])
            if not ok:
                logger.error(
                    'failed to verify OTP `{0}` as valid for enrollment `{1}`'.
                    format(data['token'], enrollment.pk))
                return False, errors.MFASecurityError(
                    'token mismatch: `{0}` is not a valid OTP token for enrollment `{1}`'
                    .format(data['token'], enrollment.pk))

            # extract the device details
            details = OTPDeviceDetails(
                data={
                    'issuer_name': private_details['issuer_name'],
                    'digits': private_details['digits'],
                    'interval': private_details['interval'],
                    'secret': private_details['secret'],
                    'valid_window': private_details['valid_window'],
                    'algorithm': private_details['algorithm']
                })

            if not details.is_valid():
                logger.info(
                    'could not validate OTP device details: {0}'.format(
                        details.errors))

            # create the device
            device = Device()
            device.name = 'OTP [{0}]'.format(enrollment.username)
            device.kind = enrollment.device_selection.kind
            device.enrollment = enrollment

            # save the device details
            device.details = details.validated_data

            return device, None
コード例 #16
0
ファイル: email.py プロジェクト: andrewkrug/oss2fa
    def enrollment_complete(self, enrollment, data):
        assert enrollment.status == Enrollment.STATUS_IN_PROGRESS
        assert not enrollment.is_expired()

        # compare given token to privately stored token
        private_details = EmailDeviceEnrollmentPrivateDetails(
            data=enrollment.private_details)
        if not private_details.is_valid():
            return None, errors.MFAInconsistentStateError(
                'enrollment private details is invalid: {0}'.format(
                    private_details.errors))

        # if the token don't match, fail.
        if private_details.validated_data['token'] != data['token']:
            return None, errors.MFASecurityError(
                'token mismatch, expected `{0}` however received `{1}`'.format(
                    private_details.validated_data['token'], data['token']))

        # extract the device details
        details = EmailDeviceDetails(
            data={'address': private_details.validated_data['address']})

        assert details.is_valid()

        # create the device
        device = Device()

        device.name = u'Email [@{0}]'.format(
            EmailDeviceKindModule.mask_address(
                private_details.validated_data['address']))

        device.kind = enrollment.device_selection.kind
        device.enrollment = enrollment

        # save the device details
        device.details = details.validated_data

        return device, None
コード例 #17
0
 def handle(self, *args, **options):
     device = Device()
     device.save()
コード例 #18
0
 def handle(self, *args, **options):
     Stat.load_initial_data()
     Device.load_initial_data()
     self.stdout.write(
         self.style.SUCCESS('Successfully created basic data'))
コード例 #19
0
ファイル: views.py プロジェクト: sylpi10/django_course
def device_add(request, os, model):
    device = Device(os=os, model=model)
    device.save()
    return HttpResponse("created device {}".format(device))
コード例 #20
0
    ip_address = str(process.read())[:-1]  #Removes the space at the end
    return ip_address


local_device_ip = get_local_ip()
local_scanner = NetworkScanner(get_local_ip())
arp_output = local_scanner.get_devices_on_network("-sn", "-a -n")
ips = local_scanner.format_to_get_ip(arp_output)[:-2]
# ips = local_scanner.check_if_identifier_broadcast(ips)
macs = local_scanner.format_to_get_mac(arp_output)[:-2]
vendors = local_scanner.get_vendor_by_mac(macs)
mobile, iphone, android = NetworkScanner.detect_mobile(ips)
ports_open = local_scanner.detect_open_common_ports(ips)
print(arp_output)
print(ips)
print(macs)
print(vendors)

for i in range(len(ips)):
    device = Device()
    device.ip_address = ips[i]
    device.mac_address = macs[i]
    device.vendor = vendors[i]
    device.mobile = mobile[i]
    device.port = ports_open[i]
    device, created = Device.objects.update_or_create(
        ip_address=device.ip_address,
        mac_address=device.mac_address,
        vendor=device.vendor,
        mobile=device.mobile,
        port=device.port)
コード例 #21
0
#!/usr/bin/env python3

from devices.models import Device, Sensor, Measurement
import random

device1 = Device(name="DummyDevice1",
                 id="cbb4f156-70ba-453c-ba47-4ec2301b654c",
                 description="Dummy device for displaying fake data.")
device1.save()

sensor11 = Sensor(name="DummySensor1", parent=device1)
sensor11.save()

for _ in range(45):
    value = random.randint(15, 30)
    m = Measurement(value=value, unit="C", sensor=sensor11)
    m.save()

device2 = Device(name="DummyDevice2",
                 id="0bc25db7-c44e-4e94-9305-b377bd5f6e72",
                 description="Dummy device for displaying fake data.")
device2.save()

sensor21 = Sensor(name="DummySensor1", parent=device2)
sensor21.save()

for _ in range(45):
    value = random.randint(-15, 15)
    m = Measurement(value=value, unit="C", sensor=sensor21)
    m.save()
コード例 #22
0
def list():
    devices = Device.query.filter_by(user_id=g.auth['sub']).all()
    return jsonify({
        'devices': Device.serialize_list(devices,('user','shares'))
    })
コード例 #23
0
 def test_registered_is_false_by_default(self):
     device = Device(name="device_a",
                     description="device description",
                     serial_id="abc",
                     address="abc")
     self.assertFalse(device.registered)
コード例 #24
0
 def test_cannot_save_with_blank_columns(self):
     device = Device(name="device_a", description="device description")
     with self.assertRaises(ValidationError):
         device.save()
         device.full_clean()
コード例 #25
0
ファイル: tests.py プロジェクト: bwghughes/roomysite
 def test_repr_looks_ok(self):
     device = Device()
     device.name = "Device 1"
     device.registered_at = timezone.now()
     self.assertTrue(unicode(device).startswith("Device 1 -"))
コード例 #26
0
def setup_device():
        device = Device()
        device.user = setup_admin()
        device.name = 'Testdevice'
        device.type = 'RPB'
        device.wifi_chip = 'Atheros'
        device.os = 'Debian'
        device.description = 'This is a test device.'
        device.tags = ['test','zurich','othertag']
        device.latitude = '40.0'
        device.longitude = '83.0'
        device.save()
        return device