4

首先,我在网上和 stackoverflow 上搜索了大约 3 天,但没有找到我一直在寻找的任何东西。

我正在进行每周一次的安全审计,我会在其中取回一个带有 IP 和开放端口的 .csv 文件。它们看起来像这样:

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

不同的是: 10.12.7.8 :23关闭了。 10.24.0.2:2210.75.1.0:23 已​​打开。

我想要一个打印出来的脚本:

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

我怎样才能制作这样的脚本?我尝试了我的 difflib,但这不是我需要的。我还需要能够稍后将其写入文件或将该输出作为我已经有脚本的邮件发送。

我不能使用 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 回答 3

3

In the following solution I've used sets, so the order doesn't matter and we can do direct subtraction with the old and new to see what has changed.

I've also used the with context manager pattern for opening files, which is a neat way of ensuring they are closed again.

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')))

Obviously you could print out the diff string if you wanted to.

于 2016-10-06T10:14:50.363 回答
1

使用您的代码作为基础,您可以执行以下操作:

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))

这里有一些调整:

  1. 我们想读取新旧文件的各个行以进行比较。
  2. 我们不必strip像在读取文件时那样对每一行进行处理。
  3. 我们使用{}and.format()来构建文本字符串。
  4. 使用\n确保我们将每个条目放在输出文件的新行上。
  5. 使用with我们正在写入的文件让我们无需调用即可打开它,close并且(如果我的知识是正确的)允许在打开文件后更好地处理任何程序崩溃。
于 2016-10-06T10:12:17.703 回答
0

你可以试试这个:

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()
于 2016-10-06T10:12:46.027 回答