在运维过程中,难免需要对比不同时间段修改的配置文件来确定一个服务到底修改了那些内容,最新一次变动还需要改动那些内容。而python3中的difflib模块则有十分强大的文件差异对比的功能,其中的HtmlDiff()方法可以生成已经对比好的html文件,方便我们进行阅读。
脚本设计流程:
下面就贴上脚本的源代码:
import difflib
import sys
try:
textfile1 = input("Please input your config file1>>:")
textfile2 = input("Please input your config file2>>:")
except Exception as e:
print("Error" + str(e))
sys.exit()
def readfile(filename):
try:
file_obj = open(filename, 'r')
text = file_obj.read().splitlines()
file_obj.close()
return text
except IOError as e:
print("Error" + str(e))
sys.exit()
def make_html_file(filename1, filename2):
try:
diff_obj = difflib.HtmlDiff()
html_context = diff_obj.make_file(filename1, filename2)
return html_context
except Exception as e:
print("Error" + str(e))
sys.exit()
def save_html_file(context, file_path):
try:
file_obj = open(file_path, 'w')
for line in context:
file_obj.write(line)
file_obj.close()
except IOError as e:
print("IOError" + str(e))
sys.exit()
if __name__ == '__main__':
if textfile1 == "" or textfile2 == "":
print ("Please check your input")
sys.exit()
text1_context = readfile(textfile1)
text2_context = readfile(textfile2)
html_context = make_html_file(text1_context, text2_context)
save_file_path = input("Please input your html file save path>>>:")
save_html_file(html_context, save_file_path)
print("Successful!!!")