【发布时间】:2016-03-14 16:35:38
【问题描述】:
您好,我有一个 python 脚本,它可以将时间、日期 + ip 地址放入字典中,但我想将其拆分,以便使输出看起来更好。目前的输出是
on ('Feb 4 10', '85.17.188.70') There was 2 attacks with ('Feb 4 10', '85.17.188.70')
on ('Feb 3 08', '211.167.103.172') There was 172 attacks with ('Feb 3 08', '211.167.103.172')
on ('Feb 4 08', '1.234.51.243') There was 15 attacks with ('Feb 4 08', '1.234.51.243')
但我想说:
2 月 4 日 08 时有 2 次攻击,IP 地址为 85.17.188.70。
我的代码如下:
myAuthlog=open('auth.log', 'r')
counter_IP = 0
desc_ip = {}
for line in myAuthlog.readlines():
list_of_line = line.split(' ')
#Start of method for attacks per hour, per IP
#we are working backwards to avoid the difference of the length of the logs
attack_ip_and_time = list_of_line[-4] #attack_ip_and_time is equal to list_of_line but working backwards so will work 4 spaces back.
attack_ip_address_list= attack_ip_and_time.split('port') #it will know split the line after the word 'port' and be called attack_ip_address_list
attack_ip_address = attack_ip_address_list[0] #attack_ip_address is now equal to attack_ip_address_list
perhour = line[0:9]
if 'Failed password for' in line: # If 'Failed password for' is in the line then:
print '\'',attack_ip_address,'\''
print '\'', perhour, '\''
if (perhour, attack_ip_address) in desc_ip: #if desc_ip has 'attack_ip_address' available in the dictionary then:
count_ip = desc_ip[perhour, attack_ip_address] #count_ip equals desc_ip[attack_ip_address]
count_ip = count_ip +1 # every time there is an occurrence the counter goes up by 1
desc_ip[perhour, attack_ip_address] = count_ip #desc_ip[attack_ip_address] will now equal the counter count_ip =0 #zero out the temporary counter as a precaution
else: # if 'attack_ip_address' is not available in 'desc_ip' then:
desc_ip[perhour, attack_ip_address] = 1 # if 'attack_ip_address' is not available in the dictionary then desc_ip[attack_ip_address] will equal 1
#End of method for attacks per hour, per IP
print '\nNumber of attacks per hour per IP:' #prints the tet
for desc_item in desc_ip.keys(): # for description items that are stored in ip dictionary
print 'on', desc_item, 'There was', desc_ip[desc_item],' attacks with ', desc_item, ''
print ''
有什么方法可以拆分这本字典以产生这种结果?
到 auth.log 的示例输出
Feb 5 08:33:15 j4-be02 sshd[2255]: Failed password for root from 5.199.133.223 port 48154 ssh2
Feb 5 08:33:23 j4-be02 sshd[2257]: Failed password for root from 5.199.133.223 port 55109 ssh2
Feb 5 08:33:30 j4-be02 sshd[2259]: Failed password for root from 5.199.133.223 port 62058 ssh2
【问题讨论】:
-
能否提供词典样本?
-
在字典里面是 ('Feb 4 10', '85.17.188.70') 日期时间和 IP 地址
-
我认为您可以改进从日志行中提取时间和 ip 的方式。请在
auth.log中发布示例日志消息。 -
Feb 5 08:33:15 j4-be02 sshd[2255]:来自 5.199.133.223 端口 48154 ssh2 的 root 密码失败 2 月 5 日 08:33:23 j4-be02 sshd[2257]:失败来自 5.199.133.223 端口 55109 ssh2 的 root 密码 2 月 5 日 08:33:30 j4-be02 sshd[2259]:来自 5.199.133.223 端口 62058 ssh2 的 root 密码失败
标签: python apache dictionary logging