如何完全備份android系統上的system分區和data分區
安卓的系統備份在很多場合下可能會用到,下面這個python的指令碼,可以用來備份整個的data分區:將所有data分區的檔案和目錄打包到data.zip,並產生recovery的專用edify指令碼到update-script.sh。當然,簡單的修改下指令碼的備份路徑就可以備份system分區了,如果再加上幾行代碼,就可以備份boot,recovery,uboot等等分區,不過這要根據不同的分區來寫不同的備份代碼:
backup.py
import sysimport osfrom os.path import joinfrom os import pathimport zipfilefrom zipfile import ZipFiledef 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上通過命令列的方式執行。