Skip to main content
 首页 » 编程设计

python之一旦我有主机名就比较文件

2025年02月15日15zengkefu

我需要一种方法来比较两个具有相同主机名的文件。我写了一个函数来解析主机名并将其保存在列表中。完成后,我需要能够比较文件。

每个文件都在不同的目录中。

第一步:从每个文件中检索“主机名”。 第二步:对两个目录中具有相同“主机名”的文件运行比较。

检索主机名代码:

def hostname_parse(directory): 
    results = [] 
    try: 
        for filename in os.listdir(directory): 
            if filename.endswith(('.cfg', '.startup', '.confg')): 
                file_name = os.path.join(directory, filename) 
                with open(file_name, "r") as in_file: 
                    for line in in_file: 
                        match = re.search('hostname\s(\S+)', line) 
                        if match: 
                            results.append(match.group(1)) 
                            #print "Match Found" 
        return results 
    except IOError as (errno, strerror): 
        print "I/O error({0}): {1}".format(errno, strerror) 
        print "Error in hostname_parse function" 

示例数据:

测试文件:

19-30# 
! 
version 12.3 
service timestamps debug datetime msec 
service timestamps log datetime msec 
service password-encryption 
! 
hostname 19-30 
! 
boot-start-marker 
boot-end-marker 
! 
ntp clock-period 17179738 
ntp source Loopback0 
! 
end 
 
19-30# 

在这种情况下,主机名是 19-30。为了便于测试,我只使用了相同的文件,但将其修改为相同或不同。

如上所述。我可以提取主机名,但我现在正在寻找一种方法,然后根据找到的主机名比较文件。

它的核心是文件比较。然而,能够查看特定领域将是我想要完成的。对于初学者,我只是想看看文件是否相同。区分大小写无关紧要,因为这些是思科生成的具有相同格式的文件。文件的内容更为重要,因为我正在寻找“配置”更改。

请您参考如下方法:

这里有一些代码可以满足您的要求。我没有办法测试,所以它可能有一些挑战。使用哈希库计算文件内容的哈希值,作为查找更改的一种方式。

import hashlib 
import os 
import re 
 
HOSTNAME_RE = re.compile(r'hostname +(\S+)') 
 
def get_file_info_from_lines(filename, file_lines): 
    hostname = None 
    a_hash = hashlib.sha1() 
    for line in file_lines: 
        a_hash.update(line.encode('utf-8')) 
        match = HOSTNAME_RE.match(line) 
        if match: 
            hostname = match.group(1) 
    return hostname, filename, a_hash.hexdigest() 
 
def get_file_info(filename): 
    if filename.endswith(('.cfg', '.startup', '.confg')): 
        with open(filename, "r") as in_file: 
            return get_file_info_from_lines(filename, in_file.readlines()) 
 
def hostname_parse(directory): 
    results = {} 
    for filename in os.listdir(directory): 
        info = get_file_info(filename) 
        if info is not None: 
            results[info[0]] = info 
    return results 
 
results1 = hostname_parse('dir1') 
results2 = hostname_parse('dir2') 
 
for hostname, filename, filehash in results1.values(): 
    if hostname in results2: 
        _, filename2, filehash2 = results2[hostname] 
        if filehash != filehash2: 
            print("%s has a change (%s, %s)" % ( 
                hostname, filehash, filehash2)) 
            print(filename) 
            print(filename2) 
            print()