当我们维护多个Nginx配置文件时,时常会对比不通版本配置文件的差异,使运维人员更加清晰的了解不通版本迭代后的更新项,实现的思路是读取两个需对比的配置文件,再以换行符作为分隔符,调用difflib.HtmlDiff()生产HTML格式的差异文档。实现的代码如下:
[root@localhost ~]# cat diff.py
1. #!/usr/bin/python
2. #coding:utf-8
3.
4. import difflib
5. import sys
6. try:
7. #第一个配置文件路径参数
8. textfile1=sys.argv[1]
9. #第二个配置文件路径参数
10. textfile2=sys.argv[2]
11. except Exception,e:
12. print "Error:"+str(e)
13. print "Usage: simple3.py filename1 filename2"
14. sys.exit()
15. #文件读取分隔函数
16. def readfile(filename):
17. try:
18. fileHandle = open (filename, 'rb' )
19. #读取后以行进行分隔
20. text=fileHandle.read().splitlines()
21. fileHandle.close()
22. return text
23. except IOError as error:
24. print('Read file Error:'+str(error))
25. sys.exit()
26. if textfile1=="" or textfile2=="":
27. print "Usage: diff.py filename1 filename2 >diff.html"
28. sys.exit()
29. #调用readfile函数,获取分隔后的字符串
30. text1_lines = readfile(textfile1)
31. text2_lines = readfile(textfile2)
32. #创建HtmlDiff()类对象
33. d = difflib.HtmlDiff()
34. #通过make_file方法输出HTML格式的比对结果
35. print d.make_file(text1_lines, text2_lines)
[root@localhost ~]# python diff.py nginx.conf nginx.conf1 >diff.html
[root@localhost ~]# \cp diff.html /usr/local/nginx/html/
#运行结果如下: