XTOOLS【运维平台】之文件OR目录压缩(二)《本地压缩和远程压缩实现》
逻辑实现难点伪代码分享
逻辑实现
Al本地压缩AND远程压缩
难点
远程服务器执行的底层公共函数
远程服务器无法直接使用tarfile、zipfile第三方模块
伪代码分享
本地tar
import tarfile
def tar_compress(src_path, dest_path, pg_name):
output_filename = dest_path + pg_name
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(src_path, arcname=os.path.basename(src_path))
新知识点:
tarfile
第三方模块的使用
本地zip
import zipfile
import os
def zip_compress(src_path, dest_path, pg_name):
output_filename = dest_path + pg_name
zipf = zipfile.ZipFile(output_filename, 'w')
pre_len = len(os.path.dirname(src_path))
for parent, dirnames, filenames in os.walk(src_path):
for filename in filenames:
pathfile = os.path.join(parent, filename)
arcname = pathfile[pre_len:].strip(os.path.sep)
zipf.write(pathfile, arcname)
zipf.close()
新知识点:
zipfile
第三方模块的使用目录递归的实现,
os.walk
的使用
远程tar&zip 合二为一,底层在Ansible实现
def tar_compress_remote(ips, src_path, dest_path, pg_name, exclude_path='', compresstype='gz'):
output_filename = dest_path + pg_name
create_archive = [
{'action': {'module': 'archive', 'args': 'path=' + src_path + ' dest=' + output_filename + ' format=' + compresstype},
'name': 'create_archive'},
]
print('create_archive:', create_archive)
hosts = toolset_views.hosts_compose(ips, ansible_ssh_user='root')
result = exec_ansible(data=hosts, tasks=create_archive)
return result
新知识点:
Ansible
API接口实现tar
&zip
两个方法,上层使用传递参数即可
Ansible
API接口的想实现较完善的功能,比较复杂,对新手较难
前端UI的实现