python练习题

1.监控日志的脚本:

  如果同一个ip地址60s之内访问超过200次,那么就把ip加入黑名单里

  需求分析:

    1.60秒读一次文件

    2.分割,取到第一个元素,ip地址

    3.把所有的ip加入到list里,如果ip次数超过200次,加入黑名单

access.log的样式:

121.69.45.254 - - [04/Jun/2017:10:38:31 +0800] "POST /dsx/wp-admin/admin-ajax.php HTTP/1.1" 200 47 "http://www.imdsx.cn/dsx/wp-admin/post.php?post=723&action=edit" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" "-"
42.236.49.31 - - [04/Jun/2017:10:40:01 +0800] "GET /questions HTTP/1.1" 200 41977 "http://bbs.besttest.cn/questions" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36; 360Spider" "-"

 

 1 import time
 2 point=0#文件指针
 3 while True:
 4     ips=[]#存放所有的ip地址
 5     blk_set = set()#存放需要加入黑名单ip
 6     with open('access.log',encoding='utf-8')as f:
 7         f.seek(point)
 8         for line in f:
 9             ip=line.split()[0]
10             ips.append(ip)
11             if ips.count(ip)>10:
12                 blk_set.add(ip)
13         for ip in blk_set:#这里是因为防止ip重复加入黑名单,因为集合是去重的,所以里面没有重复的ip
14             print('已经把%s加入黑名单'%ip)
15         point=f.tell()
16         time.sleep(60)

 2.对比请求报文:对比俩字典里面不一样的值

  需求分析:
    1.循环第一个字典,取到k。然后从第二个字典里面取值,然后判断两个值是否一样

 1 d1={'a':1,'b':2,'f':5}
 2 d2={'s':3,'b':4}
 3 def compare(d1,d2):
 4     for k in d1:
 5         v1=d1.get(k)
 6         v2=d2.get(k)
 7         if v2:
 8             if v1!=v2:
 9                 print('value不一样的k是%s,v1是%s,v2是%s'%(k,v1,v2))
10         else:
11             print('key不一样是%s'%k)
12 compare(d1,d2)

3.类型判断:

 1 if type(d1)==dict:
 2     print('字典')
 3 
 4 def print_var_type(var):
 5     if type(var)==str:
 6         print('字符串')
 7     elif type(var)==dict:
 8         print('字典')
 9     elif type(var)==int:
10         print('整数')
11     elif type(var)==list:
12         print('列表')
13     elif type(var) ==tuple:
14         print('元组')
15     elif type(var) ==float:
16         print('小数类型')
17     elif type(var) ==set:
18         print('集合')

 4.

#1.写一个校验字符串是否为合法的小数
#0.88
#-0.99
#1.小数点的个数,小数点的个数1
#2.按照小数点分割
 1 def check_float(s):
 2     s=str(s)
 3     if s.count('.')==1:
 4         s_list=s.split('.')
 5         left=s_list[0]
 6         right=s_list[1]
 7         if left.isdigit()and right.isdigit():#正小数
 8             return True
 9         elif left.startswith('-')and left.count('-')==1:
10             if left.split('-')[-1].isdigit()and right.isdigit():
11                 return True
12     return False
13 print(check_float(1.5))
14 print(check_float(-1.5))
15 print(check_float(2))
16 print(check_float('s.8'))
17 print(check_float('.8'))
18 print(check_float(.8))
19 print(check_float('.'))
20 print(check_float('-.5'))
21 print(check_float('-5.-5'))

 

posted @ 2018-01-07 23:57  飞鸟与新月  阅读(1213)  评论(0编辑  收藏  举报