示例#1
0
文件: utils.py 项目: reedy/MAD
def get_apk_info(downloaded_file: io.BytesIO) -> Tuple[str, str]:
    package_version: str = None
    package_name: str = None
    try:
        apk = apkutils.APK(downloaded_file)
    except:  # noqa: E722 B001
        logger.warning('Unable to parse APK file')
    else:
        manifest = apk.get_manifest()
        try:
            package_version, package_name = (manifest['@android:versionName'],
                                             manifest['@package'])
        except (TypeError, KeyError):
            logger.debug("Invalid manifest file. Potentially a split package")
            with zipfile.ZipFile(downloaded_file) as zip_data:
                for item in zip_data.infolist():
                    try:
                        with zip_data.open(item, 'r') as fh:
                            apk = apkutils.APK(io.BytesIO(fh.read()))
                            manifest = apk.get_manifest()
                            try:
                                package_version = manifest[
                                    '@android:versionName']
                                package_name = manifest['@package']
                            except KeyError:
                                pass
                    except (BadZipFile, LargeZipFile):
                        continue
    return package_version, package_name
示例#2
0
def get_apk_activity(path):
    tmp = apkutils.APK(path).get_manifest()
    data = tmp['application']['activity']
    activity_list = []
    for activity in data:
        activity_list.append(activity['@android:name'])
    return activity_list
示例#3
0
def get_apk_info(path):
    tmp = apkutils.APK(path).get_manifest()
    info = {}
    info['versionCode'] = str(tmp.get('@android:versionCode'))
    info['versionName'] = str(tmp.get('@android:versionName'))
    info['package'] = str(tmp.get('@package'))
    return info
示例#4
0
    def parse(self, stream, media_type=None, parser_context=None):
        """ Parse uploaded APK files. """

        data_and_files = super().parse(stream, media_type, parser_context)

        files = data_and_files.files
        if len(files) > 1:
            raise ParseError('More then one file received.')
        file_desc = next(files.values())

        # read and parse app parameters from APK manifest
        try:
            apk = apkutils.APK(file_desc.file)
            manifest = apk.get_manifest()
            package_name = manifest.get('@package')
            package_version_code = manifest.get('@android:versionCode')
        except apkutils.apkfile.BadZipFile:
            raise ParseError('Failed to parse APK file: unknown file format.')

        # update the 'data' dict with new values from manifest
        data_and_files.data._mutable = True
        data_and_files.data['package_name'] = package_name
        data_and_files.data['package_version_code'] = package_version_code

        return data_and_files
示例#5
0
 def __init__(self, path_to_apk: str):
     """
     Инициализируем сущность
     :param path_to_apk: (str) путь к .apk
     """
     self._apk = apkutils.APK(path_to_apk)
     self._manifest = self._apk.get_manifest()
     if not self._manifest:
         raise RuntimeError("Could not recognize file as Android APK")
     self.apk_opener = APKOpener(os.path.abspath(path_to_apk))
示例#6
0
 def get_apk_info(self, downloaded_file: io.BytesIO) -> NoReturn:
     try:
         apk = apkutils.APK(downloaded_file)
     except:  # noqa: E722
         logger.warning('Unable to parse APK file')
     else:
         manifest = apk.get_manifest()
         try:
             self.package_version, self.package_name = (manifest['@android:versionName'], manifest['@package'])
         except KeyError:
             raise InvalidFile('Unable to parse the APK file')
示例#7
0
def get_apk_info(path):
    '''
    获取安装包versionName,versionCode,package 等信息
    :param apk_path: apk文件本地路径
    :return: info[]
    '''
    tmp = apkutils.APK(path).get_manifest()
    info = {}
    info['versionCode'] = str(tmp.get('@android:versionCode'))
    info['versionName'] = str(tmp.get('@android:versionName'))
    info['package'] = str(tmp.get('@package'))
    return info
示例#8
0
def get_apk_info(bundle_path):
    if os.path.splitext(os.path.basename(bundle_path))[-1][1:] == 'aab':
        path = trans_aab2apk(bundle_path, config.ks_path)
    else:
        path = bundle_path

    tmp = apkutils.APK(path).get_manifest()
    info = {
        'package': str(tmp.get('@package')),
        'versionCode': str(tmp.get('@android:versionCode')),
        'versionName': str(tmp.get('@android:versionName')),
    }
    return info
 def _install_apk(self, path: str):
     try:
         m = apkutils.APK(path).manifest
         info = self._device.package_info(m.package_name)
         if info and m.version_code == info['version_code'] and m.version_name == info['version_name']:
             logger.debug("%s already installed %s", self, path)
         else:
             print(info, ":", m.version_code, m.version_name)
             logger.debug("%s install %s", self, path)
             self._device.install(path)
     except Exception as e:
         traceback.print_exc()
         logger.warning("%s Install apk %s error %s", self, path, e)
示例#10
0
def app_install_local(serial: str, apk_path: str, launch: bool = False) -> str:
    """
    install apk to device

    Returns:
        package name

    Raises:
        AdbInstallError, FileNotFoundError
    """
    # 解析apk文件
    device = adbclient.device_with_serial(serial)
    try:
        apk = apkutils.APK(apk_path)
    except apkutils.apkfile.BadZipFile:
        raise InstallError("ApkParse", "Bad zip file")

    # 提前将重名包卸载
    package_name = apk.manifest.package_name
    pkginfo = device.package_info(package_name)
    if pkginfo:
        logger.debug("uninstall: %s", package_name)
        device.uninstall(package_name)

    # 解锁手机,防止锁屏
    # ud = u2.connect_usb(serial)
    # ud.open_identify()
    try:
        # 推送到手机
        dst = "/data/local/tmp/tmp-%d.apk" % int(time.time() * 1000)
        logger.debug("push %s %s", apk_path, dst)
        device.sync.push(apk_path, dst)
        logger.debug("install-remote %s", dst)
        # 调用pm install安装
        device.install_remote(dst)
    except adbutils.AdbInstallError as e:
        raise InstallError("install", e.output)
    finally:
        # 停止uiautomator2服务
        logger.debug("uiautomator2 stop")
        # ud.session().press("home")
        # ud.service("uiautomator").stop()

    # 启动应用
    if launch:
        logger.debug("launch %s", package_name)
        device.app_start(package_name)
    return package_name
示例#11
0
 def __validate_file(self, apk_file):
     try:
         apk = apkutils.APK(apk_file)
     except:
         logger.warning('Unable to parse APK file')
         self.valid = False
     else:
         self.version = apk.get_manifest()['@android:versionName']
         self.package = apk.get_manifest()['@package']
         log_msg = 'New APK uploaded for {}'
         args = [self.filename]
         if self.architecture:
             log_msg += ' {}'
             args.append(self.architecture)
         log_msg += ' [{}]'
         args.append(self.version)
         logger.info(log_msg, *args)
示例#12
0
文件: wizard.py 项目: kimzky/MAD
    def normalize_package(self) -> NoReturn:
        """ Normalize the package

        Validate that only valid APK files are present within the package and have the correct extension.  Exclude the
        DPI APK as it is not relevant to the installation
        """
        pruned_zip = io.BytesIO()
        zout = zipfile.ZipFile(pruned_zip, 'w')
        with zipfile.ZipFile(self._data) as zip_data:
            for item in zip_data.infolist():
                try:
                    with zip_data.open(item, 'r') as fh:
                        apk = apkutils.APK(io.BytesIO(fh.read()))
                        manifest = apk.get_manifest()
                        try:
                            self.package_version = manifest[
                                '@android:versionName']
                            self.package_name = manifest['@package']
                        except KeyError:
                            pass
                    try:
                        filename = manifest['@split']
                        if filename[-3:] == 'dpi':
                            continue
                    except KeyError:
                        filename = item.filename
                    else:
                        try:
                            # The architectures use dash but we are required to use underscores
                            self.package_arch = lookup_arch_enum(
                                filename.rsplit('.', 1)[1].replace('-', '_'))
                        except (IndexError, KeyError, ValueError):
                            pass
                    if filename[-3:] != 'apk':
                        filename += '.apk'
                    zout.writestr(filename, zip_data.read(item.filename))
                except (BadZipFile, LargeZipFile):
                    continue
        zout.close()
        if not self.package_version:
            raise InvalidFile('Unable to extract information from file')
        self._data = pruned_zip
示例#13
0
def get_apk_info(path):
    tmp = apkutils.APK(path).get_manifest()
    info = {}
    info['versionCode'] = str(tmp.get('@android:versionCode'))
    info['versionName'] = str(tmp.get('@android:versionName'))
    info['package'] = str(tmp.get('@package'))
    # # 获取appkey和channel
    # data =tmp['application']['meta-data']
    # for key in data:
    #     if key['@android:name'] == 'UMENG_CHANNEL':
    #         info['channel'] = str(key['@android:value'])
    #         continue
    #     elif key['@android:name'] == 'XiaoYing_AppKey':
    #         info['appkey'] = str(key['@android:value'])
    #         continue
    # if not 'channel' in info:
    #     info['channel'] = ''
    # if not 'appkey' in info:
    #     info['appkey'] = ''
    return info
示例#14
0
def main(path):
    root = tk.Tk()

    if path:
        apk = apkutils.APK(path)
        mf = apk.manifest
        grid = TKList()
        grid.add_row(tk.Label(text="Filename"), os.path.basename(path))
        grid.add_row(tk.Label(text="Package Name"), mf.package_name)
        grid.add_row(tk.Label(text="Main Activity"), mf.main_activity)
        grid.add_row(tk.Label(text="Version Name"), mf.version_name)
        grid.add_row(tk.Label(text="Version Code"), mf.version_code)
    else:
        tk.Button(root,
                  text="Bind to *.apk Right MENU",
                  command=_bind_apk_right_menu).pack(padx=10, pady=5)
        tk.Button(root, text="Unbind", command=_unbind_reg).pack(padx=10,
                                                                 pady=5,
                                                                 side=tk.LEFT)

    tk._default_root.title("APK Parser")
    tk.mainloop()
示例#15
0
        print(f"{app_path} unzipped in {name}")
        return name
    else:
        print("Using existing zipped")
        return name


def detect_trackers(apk):
    app_dir = unzip(apk)
    tr = Trackers(app_dir, "tools")
    print("Number of known trackers", tr.nb_trackers_signature)
    print("Getting trackers")
    trackers = tr.get_trackers()
    trackers_num = len(trackers)
    print(f"We found {trackers_num} trackers:")
    score = 0
    for tracker in trackers:
        if len(tracker.categories) == 0:
            score += tracker_types["Unknown"]
        for cat in tracker.categories:
            score += tracker_types[cat]
        print(tracker.name, tracker.categories)
    if trackers_num != 0:
        print("Trackers score", round(score / trackers_num, 2))


apk_path = "app.apk"
apk = apkutils.APK(apk_path)
print("APK CATEGORY:", app_category(apk.get_manifest()["@package"]))
detect_trackers(apk_path)