【发布时间】:2018-09-25 02:02:21
【问题描述】:
我正在尝试解析日志文件并替换其中的所有 IP。这对我来说很简单,但我想做的是通过跟踪它是哪个 IP 地址来替换 IP,例如将其视为我的日志文件:
abcdef 192.168.1.1
kbckdbc 10.10.10.10
abcdef 192.168.1.1
yuosdj 100.100.100.100
我希望看到输出为:
abcdef IP_1
kbckdbc IP_2
abcdef IP_1
yuosdj IP_3
我怎样才能做到这一点?
这是我目前所拥有的:
ip_list = []
_IP_RE = re.compile(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", re.S)
counter = 0
f1 = open('logfile.txt', 'r')
for line in f1:
for matchedip in re.findall(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}",line):
if matchedip in ip_list:
matchedip = '<IP_Address_'+str(ip_list.index(matchedip)+1)+'>'
else:
counter = counter + 1
ip_list.append(matchedip)
matchedip = '<IP_Address_'+str(counter)+'>'
print matchedip
这是一个测试文件:
2018-09-13 19:00:00,317 INFO -util.SSHUtil: Waiting for channel close
2018-09-13 19:00:01,317 INFO -util.SSHUtil: Waiting for channel close
2018-09-13 19:00:01,891 INFO -filters.BasicAuthFilter: Client IP:192.168.100.98
2018-09-13 19:00:01,891 INFO -filters.BasicAuthFilter: Validating token ...
2018-09-13 19:00:01,892 INFO -authentication.Tokenization: Token:192.168.100.98:20180913_183401is present in map
2018-09-13 19:00:01,892 INFO -configure.ConfigStatusCollector: status.
2018-09-13 19:00:01,909 INFO -filters.BasicAuthFilter: Client IP:192.168.100.98
2018-09-13 19:00:01,909 INFO -filters.BasicAuthFilter: Validating token ...
2018-09-13 19:00:01,910 INFO -authentication.Tokenization: Token:192.168.100.98:20180913_183401is present in map
2018-09-13 19:00:01,910 INFO -restadapter.ConfigStatusService: configuration status.
2018-09-13 19:00:01,910 INFO -configure.Collector: Getting configuration status.
2018-09-13 19:00:02,318 INFO -util.SSHUtil: Processing the ssh command execution results standard output.
2018-09-13 19:00:02,318 INFO -util.SSHUtil: Processing the ssh command execution standard error.
2018-09-13 19:00:02,318 INFO -util.SSHUtil: Remote command using SSH execution status: Host : [10.2.251.129] User : [root] Password : [***********] Command : [shell ntpdate -u 132.132.0.88] STATUS : [0]
2018-09-13 19:00:02,318 INFO -util.SSHUtil: STDOUT : [Shell access is granted to root
14 Sep 01:00:01 ntpdate[16063]: adjust time server 132.132.0.88 offset 0.353427 sec
]
2018-09-13 19:00:02,318 INFO -util.SSHUtil: STDERR : []
2018-09-13 19:00:02,318 INFO -util.SSHUtil: Successfully executed remote command using SSH.
2018-09-13 19:00:02,318 INFO Successfully executed the command on VCenter :10.2.251.129
【问题讨论】:
-
不是一个答案,而是一个建议:由于 IPv4 是 32 位数字,因此在每个标识符中实际编码数字本身是否会有问题(如十六进制、base36 等)?例如:
192.168.1.1(0xc0a80101) 将变为IP_c0a80101(hex) 或IP_1hge135(base36)。不像IP_1、IP_2等那样易于阅读,但具有确定性和一致性。