安卓的系统备份在很多场合下可能会用到,下面这个python的脚本,可以用来备份整个的data分区:将所有data分区的文件和目录打包到data.zip,并生成recovery的专用edify脚本到update-script.sh。当然,简单的修改下脚本的备份路径就可以备份system分区了,如果再加上几行代码,就可以备份boot,recovery,uboot等等分区,不过这要根据不同的分区来写不同的备份代码:
backup.py
import sys import os from os.path import join from os import path import zipfile from zipfile import ZipFile def packdir(dir,z,dirinfo,emptydirs,linkinfo): dirs = os.listdir(dir) if not dirs: emptydirs.append(dir) else: for d in dirs: absdir = join(dir,d) if not path.islink(absdir) and (path.isdir(absdir) or path.isfile(absdir)): break else: emptydirs.append(dir) for d in dirs: absdir = join(dir,d) st = os.lstat(absdir) info = [st.st_uid,st.st_gid,st.st_mode] if path.islink(absdir): info.append(absdir) linkdir = os.readlink(absdir) linkinfo[linkdir] = info elif path.isdir(absdir): dirinfo[absdir] = info packdir(absdir,z,dirinfo,emptydirs,linkinfo) elif path.isfile(absdir): dirinfo[absdir] = info os.utime(absdir,(1403408099,1403408099)) z.write(absdir) else: print 'file type unknow %s'%(absdir,) zi = ZipFile('data.zip','w',zipfile.ZIP_DEFLATED) dirinfo = {} emptydirs = [] linkinfo = {} packdir('/data',zi,dirinfo,emptydirs,linkinfo) f = open('update-script.sh','wb'); f.write('ifelse(is_mounted("/data"),unmount("/data"),0);\n') f.write('format("ext4", "EMMC", "/dev/block/data", "0", "/data");\n') f.write('mount("ext4", "EMMC", "/dev/block/data", "/data");\n') f.write('package_extract_dir("data", "/data");\n') mkdir_cmd = 'run_program("/sbin/busybox","mkdir","-p","' mkdir_cmd += '","'.join(emptydirs) mkdir_cmd += '");\n' f.write(mkdir_cmd) for key in dirinfo.keys(): info = dirinfo[key] info = list(info) info.append(key) info = tuple(info) set_perm = 'set_perm(%d, %d, %d, "%s");\n'%info f.write(set_perm) for key in linkinfo: info = linkinfo[key] info = tuple(info) symlink = 'symlink("%s", "%s");\n'%(key,info[3]) set_perm = 'run_program("/sbin/busybox","chown","-h","install:install","%s");\n'%(info[3],) f.write(symlink) f.write(set_perm) f.write('unmount("/data");') f.close() update_script='update-script.sh' os.utime(update_script,(1403408099,1403408099)) zi.write(update_script) zi.close()
如何运行:
先要有root权限,另外,该脚本的运行依赖于python-for-android。
然后要将该脚本打包到apk里,或者在adb shell上通过命令行的方式执行。
如何完全备份android系统上的system分区和data分区
时间: 2024-10-04 16:26:39