コード例 #1
0
ファイル: usbevents.py プロジェクト: snovvcrash/usbrip
	def generate_auth_json(self, output_auth, attributes, *, indent=4, sieve=None):
		self._events_to_show = _filter_events(self._all_events, sieve)
		if not self._events_to_show:
			print_info('No USB devices found!')

		rand_id = f'usbrip-{randint(1000, 9999)}'
		self._events_to_show += [{
			'conn':     rand_id,
			'host':     rand_id,
			'vid':      rand_id,
			'pid':      rand_id,
			'prod':     rand_id,
			'manufact': rand_id,
			'serial':   rand_id,
			'port':     rand_id,
			'disconn':  rand_id
		}]

		abs_output_auth = os.path.abspath(output_auth)

		try:
			dirname = os.path.dirname(abs_output_auth)
			os_makedirs(dirname)
		except USBRipError as e:
			print_critical(str(e), initial_error=e.errors['initial_error'])
			return 1
		else:
			print_info(f'Created directory "{dirname}/"')

		try:
			auth_json = open(abs_output_auth, 'w', encoding='utf-8')
		except PermissionError as e:
			print_critical(f'Permission denied: "{abs_output_auth}". Retry with sudo', initial_error=str(e))
			return 1

		print_info('Generating authorized device list (JSON)')

		if not attributes:
			attributes = ('vid', 'pid', 'prod', 'manufact', 'serial')

		auth = defaultdict(set)
		for event in tqdm(self._events_to_show, ncols=80, unit='dev'):
			for key, val in event.items():
				if key in attributes and val is not None:
					auth[key].add(val)

		auth = {key: list(vals) for key, vals in auth.items()}

		for key in auth.keys():
			auth[key].sort()

		json.dump(auth, auth_json, sort_keys=True, indent=indent)
		auth_json.close()

		os.chmod(abs_output_auth, stat.S_IRUSR | stat.S_IWUSR)  # 600

		print_info(f'New authorized device list: "{abs_output_auth}"')
コード例 #2
0
def _output_choice(list_name, default_filename, dirname):
    while True:
        print(
            f'[?] How would you like your {list_name} list to be generated?\n')

        print('    1. JSON-file')
        print('    2. Terminal stdout')

        number = input('\n[>] Please enter the number of your choice: ')

        if number == '1':
            while True:
                filename = input(
                    f'[>] Please enter the base name for the output file '
                    f'(default is "{default_filename}"): ')

                if all(c in printable
                       for c in filename) and len(filename) < 256:
                    if not filename:
                        filename = default_filename
                    elif filename[-5:] != '.json':
                        filename = filename + '.json'

                    filename = root_dir_join(dirname + filename)

                    try:
                        dirname = os.path.dirname(filename)
                        os_makedirs(dirname)
                    except USBRipError as e:
                        print_critical(str(e),
                                       initial_error=e.errors['initial_error'])
                        return (None, '')
                    else:
                        print_info(f'Created "{dirname}"')

                    overwrite = True
                    if os.path.isfile(filename):
                        while True:
                            overwrite = input(
                                '[?] File exists. Would you like to overwrite it? [Y/n]: '
                            )
                            if len(overwrite) == 1 and overwrite in 'Yy':
                                overwrite = True
                                break
                            elif len(overwrite) == 1 and overwrite in 'Nn':
                                overwrite = False
                                break

                    if overwrite:
                        return (int(number), filename)

        elif number == '2':
            return (int(number), '')
コード例 #3
0
ファイル: usbevents.py プロジェクト: todun/usbrip
    def generate_auth_json(self,
                           output_auth,
                           attributes,
                           *,
                           indent=4,
                           sieve=None):
        self._events_to_show = _filter_events(self._all_events, sieve)
        if not self._events_to_show:
            print_info('No USB devices found!')
            return 1

        abs_output_auth = os.path.abspath(output_auth)

        try:
            dirname = os.path.dirname(abs_output_auth)
            os_makedirs(dirname)
        except USBRipError as e:
            print_critical(str(e), initial_error=e.errors['initial_error'])
            return 1
        else:
            print_info(f'Created "{dirname}"')

        try:
            auth_json = open(abs_output_auth, 'w', encoding='utf-8')
        except PermissionError as e:
            print_critical(
                f'Permission denied: "{abs_output_auth}". Retry with sudo',
                initial_error=str(e))
            return 1

        print_info('Generating authorized device list (JSON)')

        if not attributes:
            attributes = ('vid', 'pid', 'prod', 'manufact', 'serial')

        auth = defaultdict(list)
        for event in tqdm(self._events_to_show, ncols=80, unit='dev'):
            for key, val in event.items():
                if (key in attributes and val is not None
                        and val not in auth[key]):
                    auth[key].append(val)

        for key in auth.keys():
            auth[key].sort()

        json.dump(auth, auth_json, sort_keys=True, indent=indent)
        auth_json.close()

        print_info(f'New authorized device list: "{abs_output_auth}"')
コード例 #4
0
def _download_database(filename):
    try:
        dirname = os.path.dirname(filename)
        os_makedirs(dirname)
    except USBRipError as e:
        raise USBRipError(str(e),
                          errors={'initial_error': e.errors['initial_error']})
    else:
        print_info(f'Created directory "{dirname}/"')

    try:
        usb_ids = open(filename, 'w+', encoding='utf-8')
    except PermissionError as e:
        raise USBRipError(f'Permission denied: "{filename}"',
                          errors={'initial_error': str(e)})

    db, latest_ver, latest_date, errcode, e = _get_latest_version()

    if errcode:
        usb_ids.close()
        os.remove(filename)

        if errcode == USBIDs._INTERNET_CONNECTION_ERROR:
            errmsg = 'No internet connection'
        elif errcode == USBIDs._SERVER_TIMEOUT_ERROR:
            errmsg = 'Server timeout'
        elif errcode == USBIDs._SERVER_CONTENT_ERROR:
            errmsg = 'Server content error: no version or date found'

        raise USBRipError(errmsg,
                          errors={
                              'errcode': errcode,
                              'initial_error': e
                          })

    usb_ids.write(db)
    usb_ids.seek(0)

    print_info('Database downloaded')

    print(f'Version:  {latest_ver}')
    print(f'Date:     {latest_date}')

    return usb_ids