[英]Python how to split a Dictionary
您好,我有一个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
最后3行:
string_format = "on, {date}, there was {count} attacks with {ip}"
for key, count in desc_ip.iteritems():
print string_format.format(date=key[0], count=count, ip=key[1])
iteritems为您提供字典中每个元素的键和值,键的第一部分是日期,第二部分是ip。
您可以使用简单的数字访问键的各个组成部分,如下所示:
打印“上”,desc_item [0],“有”,desc_ip [desc_item],“使用IP地址的攻击”,desc_item [1],''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.