Get the difference between two files

First of all, I searched the Internet and stackoverflow for about 3 days and did not find anything I was looking for.

I do a weekly security audit where I return a CSV file with IP addresses and open ports. They look like this:

20160929.csv

10.4.0.23;22
10.12.7.8;23
10.18.3.192;23

20161006.csv

10.4.0.23;22
10.18.3.192;23
10.24.0.2;22
10.75.1.0;23

The difference is as follows: 10.12.7.8:23 is closed. 10.24.0.2:22 and 10.75.1.0:23 .

I want the script to print me:

[-] 10.12.7.8:23
[+] 10.24.0.2:22
[+] 10.75.1.0:23

How can I make a script as follows? I tried my difflib, but that is not what I need. I need to also write this later or send this output as mail, for which I already have a script.

Unix, Windows . diff .

:

old = set((line.strip() for line in open('1.txt', 'r+')))
new = open('2.txt', 'r+')
diff = open('diff.txt', 'w')

for line in new:
    if line.strip() not in old:
        diff.write(line)
new.close()
diff.close()

old = set((line.strip() for line in open('1.txt', 'r+')))
new = open('2.txt', 'r+')
diff = open('diff.txt', 'w')

for line in new:
    if line.strip() not in old:
        diff.write(line)
new.close()
diff.close()
+4
3

, :

old = set((line.strip() for line in open('1.txt')))
new = set((line.strip() for line in open('2.txt')))

with open('diff.txt', 'w') as diff:
    for line in new:
        if line not in old:
            diff.write('[-] {}\n'.format(line))

    for line in old:
        if line not in new:
            diff.write('[+] {}\n'.format(line))

:

  • , .
  • strip , , .
  • {} .format() .
  • \n , .
  • with , , close ( ) , .
+1

, , , , .

with , .

def read_items(filename):
    with open(filename) as fh:
        return {line.strip() for line in fh}

def diff_string(old, new):
    return "\n".join(
        ['[-] %s' % gone for gone in old - new] +
        ['[+] %s' % added for added in new - old]
    )

with open('diff.txt', 'w') as fh:
    fh.write(diff_string(read_items('1.txt'), read_items('2.txt')))

, diff, .

+3

:

old_f = open('1.txt')
new_f = open('2.txt')
diff = open('diff.txt', 'w')

old = [line.strip() for line in old_f]
new = [line.strip() for line in new_f]

for line in old:
    if line not in new:
        print '[-] ' + str(line)
        diff.write('[-] ' + str(line) + '\n'


for line in new:
    if line not in old:
        print '[+]' + str(line)
        diff.write('[+] ' + str(line) + '\n'

old_f.close()
new_f.close()
diff.close()
0

Source: https://habr.com/ru/post/1656915/


All Articles