提供大量第三方工具,可以开发企业级服务监控平台,本章涉及文件与目录差异对比、HTTP质量监控、邮件告警等内容
一、文件内容差异比对
1、示例1
d = difflib.Differ() diff = d.compare(text1_lines, text2_lines) print(' '.join(list(diff)))
2、示例2
import difflib text1 = """text1:""" text1_lines = text1.splitlines() text2 = """text2:""" text2_lines = text2.splitlines() d = difflib.HtmlDiff() print(d.make_file(text1_lines, text2_lines))
运行 python a.py > a.html
3、比较两个文件
import difflib import sys try: textfile1=sys.argv[1] textfile2=sys.argv[2] except Exception,e: print "Error:"+str(e) print "Usage: simple3.py filename1 filename2" sys.exit() def readfile(filename): try: fileHandle = open (filename, 'rb' ) text=fileHandle.read().splitlines() fileHandle.close() return text except IOError as error: print('Read file Error:'+str(error)) sys.exit() if textfile1=="" or textfile2=="": print "Usage: simple3.py filename1 filename2" sys.exit() text1_lines = readfile(textfile1) text2_lines = readfile(textfile2) d = difflib.HtmlDiff() print d.make_file(text1_lines, text2_lines)
运行方式, python 1.py file1 file2 > a.html
使用场景,比较不同的配置文件差异
二、目录对比模块
可以参见博客 https://www.cnblogs.com/xiao1/p/6171064.html
#!/usr/bin/env python import os, sys import filecmp import re import shutil holderlist=[] def compareme(dir1, dir2): dircomp=filecmp.dircmp(dir1,dir2) only_in_one=dircomp.left_only diff_in_one=dircomp.diff_files dirpath=os.path.abspath(dir1) [holderlist.append(os.path.abspath( os.path.join(dir1,x) )) for x in only_in_one] [holderlist.append(os.path.abspath( os.path.join(dir1,x) )) for x in diff_in_one] if len(dircomp.common_dirs) > 0: for item in dircomp.common_dirs: compareme(os.path.abspath(os.path.join(dir1,item)), os.path.abspath(os.path.join(dir2,item))) return holderlist def main(): if len(sys.argv) > 2: dir1=sys.argv[1] dir2=sys.argv[2] else: print("Usage: ", sys.argv[0], "datadir backupdir") sys.exit() source_files=compareme(dir1,dir2) dir1=os.path.abspath(dir1) if not dir2.endswith('/'): dir2=dir2+'/' dir2=os.path.abspath(dir2) destination_files=[] createdir_bool=False for item in source_files: destination_dir=re.sub(dir1, dir2, item) destination_files.append(destination_dir) if os.path.isdir(item): if not os.path.exists(destination_dir): os.makedirs(destination_dir) createdir_bool=True if createdir_bool: destination_files=[] source_files=[] source_files=compareme(dir1,dir2) for item in source_files: destination_dir=re.sub(dir1, dir2, item) destination_files.append(destination_dir) print("update item:") print(source_files) copy_pair=zip(source_files,destination_files) for item in copy_pair: if os.path.isfile(item[0]): shutil.copyfile(item[0], item[1]) if __name__ == '__main__': main()
注:这个脚本如果改到windows下使用,要注意反斜杠 " " ,不过,生产环境下,基本上碰不到windows 下的场合
一般用来做数据备份的服务,基本上都是linux,并且rysnc那个软件用得比较多