一旦我有了主机名,就可以比较文件



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

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

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

检索主机名代码:

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('hostnames(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。为了便于测试,我只是使用了相同的文件,但将其修改为相同或不相同。

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

事情的核心是文件比较。然而,能够研究特定领域将是我想要实现的。首先,我只是想看看这些文件是否相同。区分大小写并不重要,因为这些都是cisco生成的具有相同格式的文件。当我在寻找"配置"更改时,文件的内容更为重要。

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

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

相关内容

最新更新