├── .gitignore ├── .travis.yml ├── CONTRIBUTORS ├── LICENSE ├── README.md ├── android_backup ├── __init__.py ├── android_backup.py ├── pack.py ├── tests │ ├── __init__.py │ └── __main__.py └── unpack.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | 64 | .vscode 65 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | - "2.7" 5 | install: 6 | - pip install . pycrypto 7 | script: 8 | - python -mandroid_backup.tests 9 | -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | Teemu R. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2017 BlueC0re 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # android-backup-tools 2 | 3 | ![Build status](https://travis-ci.org/bluec0re/android-backup-tools.svg?branch=master) 4 | 5 | Unpack and repack android backups 6 | 7 | 8 | ## Install 9 | 10 | ``` 11 | $ pip install android_backup 12 | ``` 13 | 14 | Optional (for encrypted archives): 15 | ``` 16 | $ pip install pycrypto 17 | ``` 18 | 19 | ## Usage 20 | 21 | ### CLI 22 | 23 | #### Unpacking 24 | ``` 25 | $ android-backup-unpack foo.ab 26 | ``` 27 | 28 | Results in directory *foo.ab_unpacked* 29 | 30 | #### Packing 31 | ``` 32 | $ android-backup-pack foo.ab 33 | ``` 34 | 35 | Packs *foo.ab_unpacked* folder to *foo.ab*. Requires a previously generated *foo.ab.pickle* file. 36 | 37 | ### Programmatic 38 | 39 | ```python 40 | from android_backup import AndroidBackup, CompressionType, EncryptionType 41 | 42 | with AndroidBackup('foo.ab') as ab: 43 | ab.list() # print content to stdout 44 | 45 | with AndroidBackup('foo.ab') as ab: 46 | ab.unpack() 47 | 48 | ab = AndroidBackup() 49 | ab.version = 3 50 | ab.compression = CompressionType.ZLIB 51 | ab.encryption = EncryptionType.NONE 52 | ab.pack('foo.ab') 53 | ``` 54 | -------------------------------------------------------------------------------- /android_backup/__init__.py: -------------------------------------------------------------------------------- 1 | from .android_backup import AndroidBackup, CompressionType, EncryptionType 2 | -------------------------------------------------------------------------------- /android_backup/android_backup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # License: Apache-2.0 4 | import tarfile 5 | import zlib 6 | import enum 7 | import io 8 | import pickle 9 | import os 10 | import getpass 11 | import binascii 12 | import sys 13 | 14 | try: 15 | from Crypto.Cipher import AES 16 | from Crypto.Protocol.KDF import PBKDF2 17 | from Crypto import Random 18 | except ImportError: 19 | AES = None 20 | 21 | 22 | class CompressionType(enum.IntEnum): 23 | NONE = 0 24 | ZLIB = 1 25 | 26 | 27 | class EncryptionType(enum.Enum): 28 | NONE = 'none' 29 | AES256 = 'AES-256' 30 | 31 | 32 | class Proxy: 33 | """ 34 | Proxy class for applying a transformer function around each read call 35 | """ 36 | def __init__(self, transformer, source, chunk_size=4096): 37 | self.transformer = transformer 38 | self.source = source 39 | self.pos = 0 40 | self._buffer = bytearray() 41 | self.chunk_size = chunk_size 42 | 43 | def read(self, n=0): 44 | data = self._buffer 45 | if len(data) < n: 46 | for chunk in iter(lambda: self.source.read(self.chunk_size), b''): 47 | res = self.transformer(chunk) 48 | if not res: 49 | break 50 | data.extend(res) 51 | if n and len(data) >= n: 52 | break 53 | else: 54 | pass 55 | #raise IOError("No data after {} bytes, was expecting another {} bytes".format(self.pos, n - len(data))) 56 | 57 | if len(data) > n: 58 | self._buffer = data[n:] 59 | data = data[:n] 60 | else: 61 | self._buffer = bytearray() 62 | 63 | self.pos += len(data) 64 | return bytes(data) 65 | 66 | def tell(self): 67 | return self.pos 68 | 69 | 70 | class AndroidBackup: 71 | """ 72 | Handles android backup files (.ab). 73 | 74 | Supports compression and AES encryption (via pycrypto) 75 | 76 | >>> with AndroidBackup('backup.ab') as ab: 77 | >>> ab.list() 78 | """ 79 | def __init__(self, fname=None, password=None, stream=True): 80 | """ 81 | :param fname: The filename of the backup file or a file-like object 82 | :param password: The password to use for the en-/decryption 83 | :param stream: Open the backup file in stream mode. Reduces memory usage 84 | but allows only sequential reads. Default: True 85 | """ 86 | self.fname = 'unknown' 87 | self.fp = None 88 | self.version = None 89 | self.compression = None 90 | self.encryption = None 91 | self.stream = stream 92 | self.password = password 93 | # position of the actual file data (after the header) 94 | self.__data_start = 0 95 | 96 | if isinstance(fname, str): 97 | self.open(fname) 98 | self.fname = fname 99 | else: 100 | self.fp = fname 101 | if hasattr(self.fp, 'name'): 102 | self.fname = self.fp.name 103 | 104 | def open(self, fname, mode='rb'): 105 | """ 106 | (Re-)opens a backup file 107 | """ 108 | self.close() 109 | self.fp = open(fname, mode) 110 | self.fname = fname 111 | 112 | def close(self): 113 | """ 114 | Closes the filedescriptor for a backup file 115 | """ 116 | if self.fp is not None: 117 | self.fp.close() 118 | 119 | def is_encrypted(self): 120 | """ 121 | Returns True if the header indicates an encryption scheme 122 | """ 123 | return self.encryption == EncryptionType.AES256 124 | 125 | def parse(self): 126 | """ 127 | Parses a backup file header. Will be done automatically if 128 | used together with the 'with' statement 129 | """ 130 | self.fp.seek(0) 131 | magic = self.fp.readline() 132 | assert magic == b'ANDROID BACKUP\n' 133 | self.version = int(self.fp.readline().strip()) 134 | self.compression = CompressionType(int(self.fp.readline().strip())) 135 | self.encryption = EncryptionType(self.fp.readline().strip().decode()) 136 | self.__data_start = self.fp.tell() 137 | 138 | def __str__(self): 139 | return '\n'.join([ 140 | "Version: {}".format(self.version), 141 | "Compression: {}".format(self.compression), 142 | "Encryption: {}".format(self.encryption), 143 | ]) 144 | 145 | def _decrypt(self, fp, password=None): 146 | """ 147 | Internal decryption function 148 | 149 | Uses either the password argument for the decryption, 150 | or, if not supplied, the password field of the object 151 | 152 | :param fp: a file object or similar which supports the readline and read methods 153 | :rtype: Proxy 154 | """ 155 | if AES is None: 156 | raise ImportError("PyCrypto required") 157 | 158 | if password is None: 159 | password = self.password 160 | 161 | if password is None: 162 | raise ValueError( 163 | "Password need to be provided to extract encrypted archives") 164 | 165 | # read the PBKDF2 parameters 166 | # salt 167 | user_salt = fp.readline().strip() 168 | user_salt = binascii.a2b_hex(user_salt) 169 | # checksum salt 170 | ck_salt = fp.readline().strip() 171 | ck_salt = binascii.a2b_hex(ck_salt) 172 | # hashing rounds 173 | rounds = fp.readline().strip() 174 | rounds = int(rounds) 175 | # encryption IV 176 | iv = fp.readline().strip() 177 | iv = binascii.a2b_hex(iv) 178 | # encrypted master key 179 | master_key = fp.readline().strip() 180 | master_key = binascii.a2b_hex(master_key) 181 | 182 | # generate key for decrypting the master key 183 | user_key = PBKDF2(password, user_salt, dkLen=256 // 8, count=rounds) 184 | # decrypt the master key and iv 185 | cipher = AES.new(user_key, 186 | mode=AES.MODE_CBC, 187 | IV=iv) 188 | master_key = bytearray(cipher.decrypt(master_key)) 189 | # format: 190 | # get IV 191 | l = master_key.pop(0) 192 | master_iv = bytes(master_key[:l]) 193 | master_key = master_key[l:] 194 | # get key 195 | l = master_key.pop(0) 196 | mk = bytes(master_key[:l]) 197 | master_key = master_key[l:] 198 | # get checksum 199 | l = master_key.pop(0) 200 | master_ck = bytes(master_key[:l]) 201 | 202 | # double encode utf8 203 | utf8mk = self.encode_utf8(mk) 204 | # calculate checksum by using PBKDF2 205 | calc_ck = PBKDF2(utf8mk, ck_salt, dkLen=256//8, count=rounds) 206 | assert calc_ck == master_ck 207 | # install decryption key 208 | cipher = AES.new(mk, 209 | mode=AES.MODE_CBC, 210 | IV=master_iv) 211 | 212 | off = fp.tell() 213 | fp.seek(0, 2) 214 | length = fp.tell() - off 215 | fp.seek(off) 216 | 217 | if self.stream: 218 | # decryption transformer for Proxy class 219 | def decrypt(data): 220 | data = bytearray(cipher.decrypt(data)) 221 | 222 | if fp.tell() - off >= length: 223 | # check padding (PKCS#7) 224 | pad = data[-1] 225 | assert data.endswith(bytearray([pad] * pad)), "Expected {!r} got {!r}".format(bytearray([pad] * pad), data[-pad:]) 226 | data = data[:-pad] 227 | 228 | return data 229 | 230 | return Proxy(decrypt, fp, cipher.block_size) 231 | else: 232 | data = bytearray(cipher.decrypt(fp.read())) 233 | pad = data[-1] 234 | assert data.endswith(bytearray([pad] * pad)), "Expected {!r} got {!r}".format(bytearray([pad] * pad), data[-pad:]) 235 | data = data[:-pad] 236 | return io.BytesIO(data) 237 | 238 | @staticmethod 239 | def encode_utf8(mk): 240 | """ 241 | (Double-)encodes the given string (masterkey) with utf-8 242 | 243 | Tries to behave like the Java implementation 244 | """ 245 | utf8mk = mk.decode('raw_unicode_escape') 246 | utf8mk = list(utf8mk) 247 | to_char = chr 248 | if sys.version_info[0] < 3: 249 | to_char = unichr 250 | for i in range(len(utf8mk)): 251 | c = ord(utf8mk[i]) 252 | # fix java encoding (add 0xFF00 to non ascii chars) 253 | if 0x7f < c < 0x100: 254 | c += 0xff00 255 | utf8mk[i] = to_char(c) 256 | return ''.join(utf8mk).encode('utf-8') 257 | 258 | def _encrypt(self, dec, password=None): 259 | """ 260 | Internal encryption function 261 | 262 | Uses either the password argument for the encryption, 263 | or, if not supplied, the password field of the object 264 | 265 | :param dec: a byte string representing the to be encrypted data 266 | :rtype: bytes 267 | """ 268 | if AES is None: 269 | raise ImportError("PyCrypto required") 270 | 271 | if password is None: 272 | password = self.password 273 | 274 | if password is None: 275 | raise ValueError( 276 | "Password need to be provided to create encrypted archives") 277 | 278 | # generate the different encryption parts (non-secure!) 279 | master_key = Random.get_random_bytes(32) 280 | master_salt = Random.get_random_bytes(64) 281 | user_salt = Random.get_random_bytes(64) 282 | master_iv = Random.get_random_bytes(16) 283 | user_iv = Random.get_random_bytes(16) 284 | rounds = 10000 285 | 286 | # create the PKCS#7 padding 287 | l = len(dec) 288 | pad = 16 - (l % 16) 289 | dec += bytes([pad] * pad) 290 | 291 | # encrypt the data 292 | cipher = AES.new(master_key, IV=master_iv, mode=AES.MODE_CBC) 293 | enc = cipher.encrypt(dec) 294 | 295 | # generate the master key checksum 296 | master_ck = PBKDF2(self.encode_utf8(master_key), 297 | master_salt, dkLen=256//8, count=rounds) 298 | 299 | # generate the user key from the given password 300 | user_key = PBKDF2(password, 301 | user_salt, dkLen=256//8, count=rounds) 302 | 303 | # encrypt the master key and iv 304 | master_dec = b"\x10" + master_iv + b"\x20" + master_key + b"\x20" + master_ck 305 | l = len(master_dec) 306 | pad = 16 - (l % 16) 307 | master_dec += bytes([pad] * pad) 308 | cipher = AES.new(user_key, IV=user_iv, mode=AES.MODE_CBC) 309 | master_enc = cipher.encrypt(master_dec) 310 | 311 | # put everything together 312 | enc = binascii.b2a_hex(user_salt).upper() + b"\n" + \ 313 | binascii.b2a_hex(master_salt).upper() + b"\n" + \ 314 | str(rounds).encode() + b"\n" + \ 315 | binascii.b2a_hex(user_iv).upper() + b"\n" + \ 316 | binascii.b2a_hex(master_enc).upper() + b"\n" + enc 317 | 318 | return enc 319 | 320 | def _decompress(self, fp): 321 | """ 322 | Internal function for decompressing a backup file with the DEFLATE algorithm 323 | 324 | :rtype: Proxy 325 | """ 326 | decompressor = zlib.decompressobj() 327 | if self.stream: 328 | return Proxy(decompressor.decompress, fp) 329 | else: 330 | out = io.BytesIO(decompressor.decompress(fp.read())) 331 | out.write(decompressor.flush()) 332 | out.seek(0) 333 | return out 334 | 335 | def read_data(self, password=None): 336 | """ 337 | Helper function which decrypts and decompresses the data if necessary 338 | and returns a tarfile.TarFile to interact with 339 | """ 340 | fp = self.fp 341 | fp.seek(self.__data_start) 342 | 343 | if self.is_encrypted(): 344 | fp = self._decrypt(fp, password=password) 345 | 346 | if self.compression == CompressionType.ZLIB: 347 | fp = self._decompress(fp) 348 | 349 | if self.stream: 350 | mode = 'r|*' 351 | else: 352 | mode = 'r:*' 353 | tar = tarfile.open(fileobj=fp, mode=mode) 354 | return tar 355 | 356 | def unpack(self, target_dir=None, password=None, pickle_fname=None): 357 | """ 358 | High level function for unpacking a backup file into the given 359 | target directory (will be generated based on the filename if not given). 360 | 361 | Creates also a filename.pickle file containing the exact order of the included files 362 | (required for repacking). 363 | 364 | :param target_dir: the directory to extract the backup file into 365 | (default: filename + _unpacked) 366 | :param password: optional password for decrypting the backup 367 | (can also be set in the constructor) 368 | """ 369 | 370 | if target_dir is None: 371 | target_dir = os.path.basename(self.fname) + '_unpacked' 372 | if pickle_fname is None: 373 | pickle_fname = os.path.basename(self.fname) + '.pickle' 374 | if not os.path.exists(target_dir): 375 | os.mkdir(target_dir) 376 | 377 | tar = self.read_data(password) 378 | members = tar.getmembers() 379 | 380 | # reopen stream (TarFile is not able to seek) 381 | tar = self.read_data(password) 382 | 383 | tar.extractall(path=target_dir, members=members) 384 | 385 | with open(pickle_fname, 'wb') as fp: 386 | pickle.dump(members, fp) 387 | 388 | def list(self, password=None): 389 | """ 390 | Lists the content of the backup to stdout 391 | """ 392 | tar = self.read_data(password) 393 | tar.list() 394 | 395 | def get_files(self, password=None): 396 | """ 397 | Returns the content of the backup file 398 | """ 399 | tar = self.read_data(password) 400 | return tar.getmembers() 401 | 402 | def pack(self, fname, source_dir=None, password=None, pickle_fname=None): 403 | """ 404 | High level function for repacking a backup file from the given 405 | target directory (will be generated based on the filename if not given). 406 | 407 | Requires also a filename.pickle file which was generated during the unpacking 408 | step. 409 | 410 | The fields `version`, `compression` and `encryption` have to be set before calling 411 | this method. 412 | 413 | :param source_dir: the directory to create the backup file from 414 | (default: filename + _unpacked) 415 | :param password: optional password for decrypting the backup 416 | (can also be set in the constructor) 417 | """ 418 | if source_dir is None: 419 | source_dir = os.path.basename(fname) + '_unpacked' 420 | if pickle_fname is None: 421 | pickle_fname = os.path.basename(fname) + '.pickle' 422 | 423 | assert self.version is not None, "Backup version is not set" 424 | assert self.compression is not None, "Compression level is not set" 425 | assert self.encryption is not None, "Encryption level is not set" 426 | 427 | data = io.BytesIO() 428 | tar = tarfile.TarFile(name=fname, 429 | fileobj=data, 430 | mode='w', 431 | format=tarfile.PAX_FORMAT) 432 | 433 | with open(pickle_fname, 'rb') as fp: 434 | members = pickle.load(fp) 435 | 436 | with open(fname, 'wb') as fp: 437 | os.chdir(source_dir) 438 | for member in members: 439 | if member.isreg(): 440 | tar.addfile(member, open(member.name, 'rb')) 441 | else: 442 | tar.addfile(member) 443 | 444 | tar.close() 445 | 446 | data.seek(0) 447 | if self.compression == CompressionType.ZLIB: 448 | compressor = zlib.compressobj(method=zlib.DEFLATED) 449 | data = compressor.compress(data.read()) + compressor.flush() 450 | if self.is_encrypted(): 451 | data = self._encrypt(data, password=password) 452 | 453 | fp.write(b'ANDROID BACKUP\n') 454 | fp.write('{}\n'.format(self.version).encode()) 455 | fp.write('{:d}\n'.format(self.compression).encode()) 456 | fp.write('{}\n'.format(self.encryption.value).encode()) 457 | 458 | fp.write(data) 459 | 460 | def __exit__(self, *args, **kwargs): 461 | self.close() 462 | 463 | def __enter__(self): 464 | self.parse() 465 | return self 466 | -------------------------------------------------------------------------------- /android_backup/pack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # License: Apache-2.0 4 | import argparse 5 | import android_backup 6 | import os 7 | import sys 8 | 9 | 10 | def _description(): 11 | plat = sys.platform 12 | supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 13 | 'ANSICON' in os.environ) 14 | is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() 15 | if not supported_platform or not is_a_tty: 16 | desc = r""" 17 | \.---./ 18 | / . . \ 19 | #| |# Android Backup 20 | #| |# Packer 21 | #|_____|# 22 | # # 23 | """ 24 | else: 25 | desc = """ 26 | \033[92m \\.---./ 27 | / . . \\ 28 | #| |# \033[94mAndroid Backup\033[92m 29 | #| |# \033[94mPacker\033[92m 30 | #|_____|# 31 | # #\033[0m 32 | """ 33 | 34 | return desc[1:] # skip empty line 35 | 36 | 37 | def main(): 38 | parser = argparse.ArgumentParser(description=_description(), 39 | formatter_class=argparse.RawDescriptionHelpFormatter) 40 | parser.add_argument('OUT') 41 | parser.add_argument('-p', '--password') 42 | parser.add_argument('-s', '--source-dir') 43 | parser.add_argument('-e', '--encrypt', action='store_true') 44 | 45 | args = parser.parse_args() 46 | 47 | ab = android_backup.AndroidBackup() 48 | ab.version = 3 49 | ab.compression = android_backup.CompressionType.ZLIB 50 | ab.encryption = android_backup.EncryptionType.NONE 51 | if args.encrypt: 52 | ab.encryption = android_backup.EncryptionType.AES256 53 | 54 | ab.pack( 55 | fname=args.OUT, 56 | source_dir=args.source_dir, 57 | password=args.password 58 | ) 59 | 60 | 61 | if __name__ == "__main__": 62 | main() 63 | -------------------------------------------------------------------------------- /android_backup/tests/__init__.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import base64 3 | import io 4 | import pickle 5 | import tarfile 6 | import time 7 | 8 | from android_backup import AndroidBackup, EncryptionType, CompressionType 9 | 10 | 11 | class UnpackTest(unittest.TestCase): 12 | # def setUp(self): 13 | # self.startTime = time.time() 14 | 15 | # def tearDown(self): 16 | # t = time.time() - self.startTime 17 | # print("%s: %.3f" % (self.id(), t)) 18 | 19 | if not hasattr(unittest.TestCase, 'assertRaisesRegex'): 20 | assertRaisesRegex = unittest.TestCase.assertRaisesRegexp 21 | 22 | def test_compressed_stream(self): 23 | with AndroidBackup(io.BytesIO(TEST_DATA_NONENC)) as ab: 24 | self.assertEqual(ab.version, 3) 25 | self.assertEqual(ab.encryption, EncryptionType.NONE) 26 | self.assertEqual(ab.compression, CompressionType.ZLIB) 27 | 28 | names = list(map(lambda f: f.name, ab.get_files())) 29 | self.assertListEqual(names, TEST_MEMBERS_NAMES) 30 | 31 | tar = ab.read_data() 32 | with self.assertRaisesRegex(tarfile.StreamError, 'seeking backwards is not allowed'): 33 | tar.extractfile( 34 | 'apps/eu.bluec0re.android-backup/r/settings.cfg').read() 35 | 36 | def test_compressed_nonstream(self): 37 | with AndroidBackup(io.BytesIO(TEST_DATA_NONENC), stream=False) as ab: 38 | self.assertEqual(ab.version, 3) 39 | self.assertEqual(ab.encryption, EncryptionType.NONE) 40 | self.assertEqual(ab.compression, CompressionType.ZLIB) 41 | 42 | names = list(map(lambda f: f.name, ab.get_files())) 43 | self.assertListEqual(names, TEST_MEMBERS_NAMES) 44 | 45 | tar = ab.read_data() 46 | tar.extractfile( 47 | 'apps/eu.bluec0re.android-backup/r/settings.cfg').read() 48 | 49 | def test_encrypted_stream(self): 50 | with AndroidBackup(io.BytesIO(TEST_DATA_ENC_TEST), password='test') as ab: 51 | self.assertEqual(ab.version, 3) 52 | self.assertEqual(ab.encryption, EncryptionType.AES256) 53 | self.assertEqual(ab.compression, CompressionType.ZLIB) 54 | 55 | names = list(map(lambda f: f.name, ab.get_files())) 56 | self.assertListEqual(names, TEST_MEMBERS_NAMES) 57 | 58 | tar = ab.read_data() 59 | with self.assertRaisesRegex(tarfile.StreamError, 'seeking backwards is not allowed'): 60 | tar.extractfile( 61 | 'apps/eu.bluec0re.android-backup/r/settings.cfg').read() 62 | 63 | def test_encrypted_nonstream(self): 64 | with AndroidBackup(io.BytesIO(TEST_DATA_ENC_TEST), password='test', stream=False) as ab: 65 | self.assertEqual(ab.version, 3) 66 | self.assertEqual(ab.encryption, EncryptionType.AES256) 67 | self.assertEqual(ab.compression, CompressionType.ZLIB) 68 | 69 | names = list(map(lambda f: f.name, ab.get_files())) 70 | self.assertListEqual(names, TEST_MEMBERS_NAMES) 71 | 72 | tar = ab.read_data() 73 | tar.extractfile( 74 | 'apps/eu.bluec0re.android-backup/r/settings.cfg').read() 75 | 76 | 77 | TEST_MEMBERS = pickle.loads(base64.b64decode(""" 78 | gAJdcQAoY3RhcmZpbGUKVGFySW5mbwpxASmBcQJOfXEDKFgEAAAAbmFtZXEEWCkAAABhcHBzL2V1 79 | LmJsdWVjMHJlLmFuZHJvaWQtYmFja3VwL19tYW5pZmVzdHEFWAQAAABtb2RlcQZNpAFYAwAAAHVp 80 | ZHEHTegDWAMAAABnaWRxCEtkWAQAAABzaXplcQlNuwVYBQAAAG10aW1lcQpKqUjwWVgGAAAAY2hr 81 | c3VtcQtN3SBYBAAAAHR5cGVxDGNfY29kZWNzCmVuY29kZQpxDVgBAAAAMHEOWAYAAABsYXRpbjFx 82 | D4ZxEFJxEVgIAAAAbGlua25hbWVxElgAAAAAcRNYBQAAAHVuYW1lcRRYCAAAAGJsdWVjMHJlcRVY 83 | BQAAAGduYW1lcRZYBQAAAHVzZXJzcRdYCAAAAGRldm1ham9ycRhLAFgIAAAAZGV2bWlub3JxGUsA 84 | WAYAAABvZmZzZXRxGksAWAsAAABvZmZzZXRfZGF0YXEbTQACWAsAAABwYXhfaGVhZGVyc3EcfXEd 85 | WAYAAABzcGFyc2VxHk51hnEfYmgBKYFxIE59cSEoaARYLgAAAGFwcHMvZXUuYmx1ZWMwcmUuYW5k 86 | cm9pZC1iYWNrdXAvci9zZXR0aW5ncy5jZmdxImgGTaQBaAdN6ANoCEtkaAlLCGgKSg9J8FloC02K 87 | ImgMaBFoEmgTaBRYCAAAAGJsdWVjMHJlcSNoFlgFAAAAdXNlcnNxJGgYSwBoGUsAaBpNAAhoG00A 88 | CmgcfXElaB5OdYZxJmJoASmBcSdOfXEoKGgEWCkAAABhcHBzL2V1LmJsdWVjMHJlLmFuZHJvaWQt 89 | YmFja3VwL2RiL2Zvby5kYnEpaAZNpAFoB03oA2gIS2RoCU0AIGgKSrpJ8FloC01LIGgMaBFoEmgT 90 | aBRYCAAAAGJsdWVjMHJlcSpoFlgFAAAAdXNlcnNxK2gYSwBoGUsAaBpNAAxoG00ADmgcfXEsaB5O 91 | dYZxLWJoASmBcS5OfXEvKGgEWCoAAABhcHBzL2V1LmJsdWVjMHJlLmFuZHJvaWQtYmFja3VwL3Nw 92 | L2Zvby54bWxxMGgGTaQBaAdN6ANoCEtkaAlLNmgKSuBJ8FloC035IGgMaBFoEmgTaBRYCAAAAGJs 93 | dWVjMHJlcTFoFlgFAAAAdXNlcnNxMmgYSwBoGUsAaBpNAC5oG00AMGgcfXEzaB5OdYZxNGJlLg== 94 | """)) 95 | TEST_MEMBERS_NAMES = list(map(lambda f: f.name, TEST_MEMBERS)) 96 | 97 | TEST_DATA_NONENC = base64.b64decode(""" 98 | QU5EUk9JRCBCQUNLVVAKMwoxCm5vbmUKeJztml2LXEUQhmdFvBgQhQjeDrlS0N2u7uov2SRGyV1u 99 | 1NyKdHVXh8XsB7OzIT/QP+I/8T2bZIlCsrIJkUg9O7Nn+nSf7vp4q88MnHZ2dn6gF/vy5EK72+p+ 100 | Oxnb06PxrbT++8XZwW/H7eRo6vludXMcSMzLkXJ0l2163l7wKYcVBcrsmH2klfOUQlxt3Fus+a+5 101 | ON+1LUx5GYDXj9Pt+RvmeeHM1fEDgdavT/46rX1c99Pjl+f3n+rJODp5vHZrWgdXvPPSL4/U2HlX 102 | nWtaZqA2KBap0Y3g3HDJVd9K4lLSzGgT/sRF5wIuCviMURWjQoyOXSKc5hhjIMJHN696guuusE89 103 | xxQ5BJd9isGREmYNFDLeLviAc6FctpcL2yu9hF7+e++7sWGJgfev9ZYWb7EsRmEu93y8a85fHgmX 104 | pZJjSYIaUKckXMfkyBQ6txJqlMiKOgkkqUfm4mvmNJ2vPtEcvrriRFsaXXrL0VOpY3iakedsCAlp 105 | n3kK7A3KFfMN8lFhOXuPRXwZ3FOqEzP6GGDF6LV6r9X3wToIxdlTiVWo1jJbLaV7RSiqJ9en69Rq 106 | TTLLaKm5rm0iurVGH/ro6jnUwmHiisGE6Ufh5EZsLddeC/IykqI/1JalZ19nUT/g/fRecscCNIKf 107 | cLBI1lG5ujokM+UcRWtWTJ4RAGRZRRFwlllVi59ELec8ecDAWGjCKYLZ8IMr4tQVC4eiOdZcIGWn 108 | MWhDpoqWqOqdIpktUBGYVwaaDL+Rggjf0KoaKjJEsxSPU6EOhLp1V3vHUM4aKbKIaIyChEnOI8IB 109 | DUu0EEZHNUMUOfW6iHDRgaM3V8wLDWFkoJQ6c2VBxKcqdYUsvU5JQ1pocD7EXnX4MSJCmCWGmboq 110 | Q64DJudR0yQkqE1mlpgUWROnpSlGVS1LQkPyqWIypCL5CPHVNtJSYBHLZykhppHqyKFB4gF1D5V1 111 | pBd6UobTLNxnChDrqCVoz01qytjzaTSeqRCXGiKJKjLPEDIUlpN6eFAiTahkyCIIaMcnhymDS6IT 112 | wVoS0Cf7HEeDLQ5yGi1zgac8VKZDiLvPPWMf4kE19YF16/QM3aekMSXBjHN2eCxSmRWKmGEIVBZQ 113 | f6kmP0KqSBbxQPZmoSXfivtToymzt4IbmqQMeQolR9Qjor3UXnYcs2dJVaYED8WGRY1Eo7ieZxu5 114 | d+iIYPSEwkKBAaNILKqDB8KtmWrPwWPtoclN7GLSWQvEXFUkaV+/k/2/XXP/3x6c626HPf98v8/H 115 | N1vjmvs/Gu7q/o+iXi17EHm7/78P5unpHWnbdyMm44PjuvofcgCJ7A95izXeXP/+slxe1n/Kfvn+ 116 | j+8kVv/vg19+eni008083R633SasPl/t7a2+32zQtYf3R68MXdof/6N9HXur/S/+/HT58NkfK7wM 117 | wzAMwzAMwzAMw7gh3+198uWtW3u/7po8UWlbvD768ecH9x892Dy6/8PDBxuc2Hx1NDZHJzt9rNtv 118 | NiftWDc7fbb7evltjh/9hmEYhmEYhmEYhmH8j7nu+Y/zs8vnP54dP7n5Gtc+/5XS1fMf+Hf5/Hcm 119 | e/7jfXB4D6ndPIVvR6cnd27Tvrt97+76cHt6uru73oBDadu7dHiwHNaHB887/murDcMwDMMwDMMw 120 | DMMwDMMwDMMwDMMwDMN4lb8AzZE8jQ== 121 | """) 122 | 123 | TEST_DATA_ENC_TEST = base64.b64decode(""" 124 | QU5EUk9JRCBCQUNLVVAKMwoxCkFFUy0yNTYKMDc3MjIzMDk2QkNERjJDQjE3QkIxQzIwM0FCMzY4 125 | NUExMjFCQkI4RTVFOTdFMjgwOERGRDY4MEIzNzlENTJBQzg5Q0M4QjM3QkU5NDBBODZFMDExRTMw 126 | M0Q0RjRCM0ZEMUYyQjEzMjlGRUI5OTE5OEE3ODUzOTM4NDE5RTc5NDAKOTRBREQ2NUIxRTJFQ0Y4 127 | ODU1QkE2NkIwRjcwNzA3ODUzODRENEM1NDJCOTQ2NEUwQTQzMDc1NEM0QjFEMjUwRkQ1Rjk3QzNE 128 | QTU0NUIzMjM3MUY3Q0E4OTBCMUQxNzhFNjg1NEZDMjVBQzQ1MkM0NTREN0NFRTE5OUJDRDM2MzkK 129 | MTAwMDAKNTk5ODMzODFCOENDMTA1Mjg1NkRGMUI0MTI1QUNGRUQKMzg1NkI3QTkzOTU5RjMzMDc4 130 | N0REMzU4MDZFMEM3QzQzOUMwOTRBRThGMDRCMDlDRjBFRTJDMjkxNjQ4MkNDRDU5QTU5NTZEMjQx 131 | N0ExREE4NEMzNTQ3MDYwRTBCRDEyNUMzQzdFRjE2NDA2MTZERkRGRTcwNzhDRjgyRUQ4QTA4RkQ2 132 | NzA3NjQ1MjA5ODgwQkIxNDg4MTdGQTgyQkUyNjMxNUU2QTI5NDBFRTQwNDZDRjQ4MEU5OUI5MEM0 133 | REM5CgLfUFnUHEXrf9rmhgXUU6zMjPNIRuxHuZzH/0UsDZJxmBkh9JhhagcZVDpRBIF52RJY/ZwP 134 | +Akygyv9/AtOcf1wY1sndEyF4E3iWBEnNzmicc9Yncl0RtWdDlF8dEW6QtgEaU67KJ+7Y75fhnhu 135 | /NrvX99Gd445mcJAur18ClJA9B4wMN7rXeiDvlIVe6h72hJ2pYGnLEdj+Y6a3tDB31CFE5J3v3nW 136 | bkqKVYh9kH/nVaDB6yljn2mU8sq62tr84lGiY/KEp7tj12b3BX61B4ZukGJnhUosNzfuPoZlli+d 137 | KiZKUmhxPJsUtcTXQh7o6eoF1i730u7hPOD4K+LKJmIVvExtMqWnZO9GlkVpt/Qj0QBSNNhhzkhc 138 | pYIDIZtA1EVVBuw+VEfBP3Lk9HO8bARM3qVHwEPWrRjOwu033X37mV8WEEPx8LOeWrl1IeiAnMdz 139 | 0YcI8rQp9ATsvvHpBdeHMjOAtx1EPwewFShMsKD2pOWSDgDhoI7yithTDIQBZyDc3SHPsW/ZFeFH 140 | Br0a2tQh08XetypZmba0S9ApjhvyPAHO+YYLW674MS72ZrSRM15YP8uH8PqkfdDxbMNEtdd8cpei 141 | e6EX2PhdG56kysbJLTfmi/r2IjmJXLO/hrTex1MOOkZoLTfTcj7msNUFHgfodApntDi6T7/kx0Im 142 | LIqEbH2PDVtY42PWWSbtuVPWhjEwR0xt+SNti8BsnVkxX3c/W5PQiw5pppSVo6xud914DMjdfygl 143 | 7doR8TfQqgXBCDO573SSvamwdu8dbnOm+3LwMotvnBvatBihWIi414iTJm+yIDCxu2iy4wfGdQ64 144 | EnhbTXbD7ffK3Z7K8spTVb/opBE3htgrmgbH2TOir0FTAwe1cTDirEbCzz7ed4lTHbMVVRzbqLFM 145 | YjXmJNgEe1km0ThdbGNzyggsDeun3EfhN6WhLfA7Rd+udffgzPtopWIIA1FwyyzFrjg+f3c6jRIf 146 | GtZKmm8VB5KXJEE+pwbluzbliBG+uMSnOd6lN2XpQmh8hiK19D2Ew4tQAKqoxbmHuV3V0RLmYSjF 147 | pADFpsx0mYIem15w1U8iL05itgJmXJmhWol0y5u3+awSAgOrXaXNlOZN8Ypp2DK9hi8bO+cp5xej 148 | BJsi6rmaxnrUG2AE407xrqGwlVVdI/Y+q3xr8iQhgGSB/HUFW+P07110rOc8vCwnUHOHttPzI8hb 149 | 6c1fjKeArXDOvgZgpw+3+4YIIIphaOn9lreDE+azMCc7hm2LaiKe14++0A8hNuzaUj9CVZvkibc4 150 | B8bbnA/BlzPodCWdW/vHin4LBhor71waris9xitIb4qVpeJKDLNLEfFjUzjhMXUMOeYUYtGmiUIr 151 | 9zCOeLHfUMgNVvBm5CUqaZYdjNAivL3iXtdVIg+uT/DEQvYST2+/n/JDV0G0VaA9X9YytP8TOL2p 152 | IW4vcpowXCIbYxUWShTdRRbbJj9S1oLsi03QRKG/KKo0TtewZmBYhImWS49bbSy+KieCMtsG77dC 153 | tks+7MVeGVykbIfXxxJ5CWbrFikQWNuQf8wndxLs0mDXIgYr6kEtN5sOk1rPLwIhiF96UMBxKH59 154 | 2jBLc8YYptcjJpencdKzlNGy0zxtZpNMrahUI8kux/7Aw9pE5lY7LucVV/0eOQ8YgKRNHtPISXqu 155 | PwCt5QihZuuFutNfk+8= 156 | """) 157 | -------------------------------------------------------------------------------- /android_backup/tests/__main__.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from . import * 4 | 5 | if __name__ == '__main__': 6 | unittest.main() 7 | -------------------------------------------------------------------------------- /android_backup/unpack.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # License: Apache-2.0 4 | import argparse 5 | from android_backup import AndroidBackup 6 | import os 7 | import sys 8 | 9 | 10 | def _description(): 11 | plat = sys.platform 12 | supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 13 | 'ANSICON' in os.environ) 14 | is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() 15 | if not supported_platform or not is_a_tty: 16 | desc = r""" 17 | \.---./ 18 | / . . \ 19 | #| |# Android Backup 20 | #| |# Unpacker 21 | #|_____|# 22 | # # 23 | """ 24 | else: 25 | desc = """ 26 | \033[92m \\.---./ 27 | / . . \\ 28 | #| |# \033[94mAndroid Backup\033[92m 29 | #| |# \033[94mUnpacker\033[92m 30 | #|_____|# 31 | # #\033[0m 32 | """ 33 | 34 | return desc[1:] # skip empty line 35 | 36 | 37 | def main(): 38 | parser = argparse.ArgumentParser(description=_description(), 39 | formatter_class=argparse.RawDescriptionHelpFormatter) 40 | parser.add_argument('-l', '--list', action='store_true') 41 | parser.add_argument('-p', '--password') 42 | parser.add_argument('-t', '--target-dir') 43 | parser.add_argument('IN', type=AndroidBackup) 44 | 45 | args = parser.parse_args() 46 | 47 | with args.IN as infile: 48 | if args.list: 49 | infile.list( 50 | password=args.password 51 | ) 52 | else: 53 | infile.unpack( 54 | target_dir=args.target_dir, 55 | password=args.password 56 | ) 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | import sys 3 | 4 | deps = [] 5 | if sys.version_info[:2] < (3,4): 6 | deps.append('enum34') 7 | 8 | setup( 9 | name='android_backup', 10 | version='0.2.0', 11 | description='Unpack and repack android backups', 12 | url='https://github.com/bluec0re/android-backup-tools', 13 | author='BlueC0re', 14 | author_email='bluec0re@users.noreply.github.com', 15 | license='Apache-2.0', 16 | classifiers=[ 17 | 'Development Status :: 3 - Alpha', 18 | 19 | 'Intended Audience :: Developers', 20 | 21 | 'License :: OSI Approved :: Apache Software License', 22 | 23 | 'Programming Language :: Python :: 2', 24 | 'Programming Language :: Python :: 3', 25 | ], 26 | packages=['android_backup'], 27 | keywords='android backup pack unpack development', 28 | entry_points={ 29 | 'console_scripts': [ 30 | 'android-backup-unpack=android_backup.unpack:main', 31 | 'android-backup-pack=android_backup.pack:main', 32 | ], 33 | }, 34 | install_requires=deps, 35 | ) 36 | --------------------------------------------------------------------------------