I have a question in regards to comparing files using python. For context, the problem I am having is that I have two firewalls with different configurations (over 14000 lines each on Notepad ) and I need to find the differences and annotate them.
Quick Example -
Firewall 1:
- Version: 123
- set policy EXPLICIT_DENY ALL
- IP address allow 1.2.3.4
- IP address allow 4.3.2.1
- set policy EXPLICIT_ALLOW NONE
Firewall 2:
- Version: 321
- set policy EXPLICIT_ALLOW NONE
- IP address allow 4.3.2.1
- IP address allow 1.2.3.4
- set policy EXPLICIT_DENY ALL
A line-by-line comparison would show that all of those lines are incorrect because they do not match side by side, however, the configuration is the same and would not need to be annotated. The only difference would be the Version # in the example. The script below was able to work for my purposes.
Current Script I ran -
'file1 = open("OLD FW.txt",'r')
'file2 = open("NEW FW.txt",'r')
'file3 = open("Results.txt",'r ')
'file1_lines = file1.readlines()
'file2_lines = file2.readlines()
'for position, a in enumerate(file1_lines):
'linematch = False
'for b in file2_lines:
'if a == b:
'linematch = True
'if linematch == False:
'file.3write(f"{position 1}: {a.strip()}\")
'file1.close()
'file2.close()'
The output would show every line from the OLD firewall that does not appear on the NEW firewall. This would effectively let me see what configurations are missing and/or different AND show me what line is is on the original FW.
The issue I figured out after coming up with this is that my current software version at work is only Python 2.7.16 which doesn't support f-strings. I did a little bit of research but am far to novice currently to figure this out in the short time window I have.
Mai question: How do I convert this Python f-string script to something that would work the same in an older version of Python that doesn't support f-strings? Thanks in advance to anyone who can help me figure this out!
CodePudding user response:
For simple cases like you show, you can use the .format()
method.
file.write("{}: {}\n".format(position 1, a.strip()))